feat: local APK build pipeline with build worker
- Build worker: Express server with JDK 17 + Android SDK - Runs expo prebuild → gradlew assembleRelease locally - Source ZIP download (instant) + APK build (async, 3-5 min) - Build status polling, APK download proxy - docker-compose for app + build-worker deployment - Gradle/SDK caches in Docker volumes for fast rebuilds
This commit is contained in:
1 parent
c7517d157f
commit
a8ce46c0af
7 files changed
+472
-24
No files matched your search
@@ -0,0 +1,45 @@
|
||||
FROM node:22-bookworm-slim
|
||||
|
||||
# Install JDK 17, Android SDK dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
openjdk-17-jdk-headless \
|
||||
wget \
|
||||
unzip \
|
||||
git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
|
||||
ENV ANDROID_HOME=/opt/android-sdk
|
||||
ENV ANDROID_SDK_ROOT=/opt/android-sdk
|
||||
ENV PATH="${ANDROID_HOME}/cmdline-tools/latest/bin:${ANDROID_HOME}/platform-tools:${PATH}"
|
||||
|
||||
# Install Android SDK command-line tools
|
||||
RUN mkdir -p ${ANDROID_HOME}/cmdline-tools && \
|
||||
wget -q "https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip" -O /tmp/cmdline-tools.zip && \
|
||||
unzip -q /tmp/cmdline-tools.zip -d ${ANDROID_HOME}/cmdline-tools && \
|
||||
mv ${ANDROID_HOME}/cmdline-tools/cmdline-tools ${ANDROID_HOME}/cmdline-tools/latest && \
|
||||
rm /tmp/cmdline-tools.zip
|
||||
|
||||
# Accept licenses and install required SDK packages
|
||||
RUN yes | sdkmanager --licenses > /dev/null 2>&1 && \
|
||||
sdkmanager "platforms;android-34" "build-tools;34.0.0" "platform-tools"
|
||||
|
||||
# Install Expo CLI and EAS CLI globally
|
||||
RUN npm install -g expo-cli@latest @expo/cli eas-cli
|
||||
|
||||
# Pre-cache Gradle wrapper (speeds up first build)
|
||||
RUN mkdir -p /tmp/gradle-cache && \
|
||||
cd /tmp/gradle-cache && \
|
||||
npm init -y && \
|
||||
npx create-expo-app@latest test-app --template blank-typescript && \
|
||||
cd test-app && \
|
||||
npx expo prebuild --platform android --no-install 2>/dev/null || true && \
|
||||
cd android && ./gradlew --version 2>/dev/null || true && \
|
||||
rm -rf /tmp/gradle-cache
|
||||
|
||||
WORKDIR /app
|
||||
COPY server.js package.json ./
|
||||
RUN npm install
|
||||
|
||||
EXPOSE 3001
|
||||
CMD ["node", "server.js"]
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "apk-forge-build-worker",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"express": "^4.21.0",
|
||||
"jszip": "^3.10.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
const express = require("express");
|
||||
const { execSync, exec } = require("child_process");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const JSZip = require("jszip");
|
||||
const crypto = require("crypto");
|
||||
|
||||
const app = express();
|
||||
app.use(express.json({ limit: "50mb" }));
|
||||
|
||||
const BUILDS_DIR = "/app/builds";
|
||||
const PROJECTS_DIR = "/app/projects";
|
||||
|
||||
// Ensure dirs exist
|
||||
fs.mkdirSync(BUILDS_DIR, { recursive: true });
|
||||
fs.mkdirSync(PROJECTS_DIR, { recursive: true });
|
||||
|
||||
// Track active builds
|
||||
const activeBuildIds = new Set();
|
||||
|
||||
// Health check
|
||||
app.get("/health", (req, res) => {
|
||||
res.json({ status: "ok", activeBuildIds: activeBuildIds.size });
|
||||
});
|
||||
|
||||
// Build APK
|
||||
app.post("/build", async (req, res) => {
|
||||
const { buildId, files, appName, packageName } = req.body;
|
||||
|
||||
if (!buildId || !files) {
|
||||
return res.status(400).json({ error: "buildId and files required" });
|
||||
}
|
||||
|
||||
// Return immediately, build async
|
||||
res.json({ status: "queued", buildId });
|
||||
|
||||
// Do the build
|
||||
activeBuildIds.add(buildId);
|
||||
const projectDir = path.join(PROJECTS_DIR, buildId);
|
||||
const statusFile = path.join(BUILDS_DIR, `${buildId}.status.json`);
|
||||
|
||||
try {
|
||||
updateStatus(statusFile, "building", "Setting up project...");
|
||||
|
||||
// Clean up any previous attempt
|
||||
if (fs.existsSync(projectDir)) {
|
||||
fs.rmSync(projectDir, { recursive: true });
|
||||
}
|
||||
fs.mkdirSync(projectDir, { recursive: true });
|
||||
|
||||
// Write all project files
|
||||
for (const [filePath, content] of Object.entries(files)) {
|
||||
const fullPath = path.join(projectDir, filePath);
|
||||
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
||||
fs.writeFileSync(fullPath, content);
|
||||
}
|
||||
|
||||
// Ensure package.json exists with Expo deps
|
||||
const pkgPath = path.join(projectDir, "package.json");
|
||||
if (!fs.existsSync(pkgPath)) {
|
||||
const pkg = {
|
||||
name: (packageName || "apk-forge-app").replace(/[^a-z0-9-]/g, "-"),
|
||||
version: "1.0.0",
|
||||
main: "expo/AppEntry.js",
|
||||
scripts: {
|
||||
start: "expo start",
|
||||
android: "expo start --android",
|
||||
ios: "expo start --ios",
|
||||
web: "expo start --web"
|
||||
},
|
||||
dependencies: {
|
||||
"expo": "~52.0.0",
|
||||
"expo-status-bar": "~2.0.0",
|
||||
"react": "18.3.1",
|
||||
"react-native": "0.76.3",
|
||||
"@react-navigation/native": "^7.0.0",
|
||||
"@react-navigation/native-stack": "^7.0.0",
|
||||
"react-native-screens": "~4.1.0",
|
||||
"react-native-safe-area-context": "~5.0.0",
|
||||
"@expo/vector-icons": "^14.0.0"
|
||||
},
|
||||
devDependencies: {
|
||||
"@babel/core": "^7.24.0",
|
||||
"typescript": "~5.3.3",
|
||||
"@types/react": "~18.2.45"
|
||||
}
|
||||
};
|
||||
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
|
||||
}
|
||||
|
||||
// Ensure app.json exists
|
||||
const appJsonPath = path.join(projectDir, "app.json");
|
||||
if (!fs.existsSync(appJsonPath)) {
|
||||
const safeName = (appName || "APK Forge App").replace(/[^a-zA-Z0-9 ]/g, "");
|
||||
const safeSlug = safeName.toLowerCase().replace(/\s+/g, "-");
|
||||
const appJson = {
|
||||
expo: {
|
||||
name: safeName,
|
||||
slug: safeSlug,
|
||||
version: "1.0.0",
|
||||
orientation: "portrait",
|
||||
icon: "./assets/icon.png",
|
||||
userInterfaceStyle: "automatic",
|
||||
newArchEnabled: true,
|
||||
splash: {
|
||||
image: "./assets/splash-icon.png",
|
||||
resizeMode: "contain",
|
||||
backgroundColor: "#1a1a2e"
|
||||
},
|
||||
android: {
|
||||
adaptiveIcon: {
|
||||
foregroundImage: "./assets/adaptive-icon.png",
|
||||
backgroundColor: "#1a1a2e"
|
||||
},
|
||||
package: packageName || `com.apkforge.${safeSlug.replace(/-/g, "")}`
|
||||
},
|
||||
plugins: ["expo-router"]
|
||||
}
|
||||
};
|
||||
fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2));
|
||||
}
|
||||
|
||||
// Create placeholder assets if missing
|
||||
const assetsDir = path.join(projectDir, "assets");
|
||||
fs.mkdirSync(assetsDir, { recursive: true });
|
||||
const placeholderPng = createPlaceholderPng();
|
||||
for (const name of ["icon.png", "splash-icon.png", "adaptive-icon.png", "favicon.png"]) {
|
||||
const p = path.join(assetsDir, name);
|
||||
if (!fs.existsSync(p)) {
|
||||
fs.writeFileSync(p, placeholderPng);
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure babel.config.js
|
||||
const babelPath = path.join(projectDir, "babel.config.js");
|
||||
if (!fs.existsSync(babelPath)) {
|
||||
fs.writeFileSync(babelPath, `module.exports = function (api) {
|
||||
api.cache(true);
|
||||
return { presets: ['babel-preset-expo'] };
|
||||
};\n`);
|
||||
}
|
||||
|
||||
// Ensure tsconfig.json
|
||||
const tsconfigPath = path.join(projectDir, "tsconfig.json");
|
||||
if (!fs.existsSync(tsconfigPath)) {
|
||||
fs.writeFileSync(tsconfigPath, JSON.stringify({
|
||||
extends: "expo/tsconfig.base",
|
||||
compilerOptions: { strict: true }
|
||||
}, null, 2));
|
||||
}
|
||||
|
||||
updateStatus(statusFile, "building", "Installing dependencies...");
|
||||
execSync("npm install", { cwd: projectDir, stdio: "pipe", timeout: 120000 });
|
||||
|
||||
updateStatus(statusFile, "building", "Generating native Android project...");
|
||||
execSync("npx expo prebuild --platform android --no-install", {
|
||||
cwd: projectDir,
|
||||
stdio: "pipe",
|
||||
timeout: 120000,
|
||||
env: { ...process.env, CI: "1", EXPO_NO_TELEMETRY: "1" }
|
||||
});
|
||||
|
||||
updateStatus(statusFile, "building", "Building APK (this takes a few minutes)...");
|
||||
execSync("cd android && chmod +x gradlew && ./gradlew assembleRelease --no-daemon -Dorg.gradle.jvmargs='-Xmx2g'", {
|
||||
cwd: projectDir,
|
||||
stdio: "pipe",
|
||||
timeout: 600000, // 10 min max
|
||||
env: { ...process.env, ANDROID_HOME: "/opt/android-sdk", JAVA_HOME: "/usr/lib/jvm/java-17-openjdk-amd64" }
|
||||
});
|
||||
|
||||
// Find the APK
|
||||
const apkDir = path.join(projectDir, "android/app/build/outputs/apk/release");
|
||||
const apkFiles = fs.existsSync(apkDir) ? fs.readdirSync(apkDir).filter(f => f.endsWith(".apk")) : [];
|
||||
|
||||
if (apkFiles.length === 0) {
|
||||
throw new Error("APK not found after build");
|
||||
}
|
||||
|
||||
// Copy APK to builds dir
|
||||
const apkSrc = path.join(apkDir, apkFiles[0]);
|
||||
const apkDst = path.join(BUILDS_DIR, `${buildId}.apk`);
|
||||
fs.copyFileSync(apkSrc, apkDst);
|
||||
|
||||
const stats = fs.statSync(apkDst);
|
||||
|
||||
updateStatus(statusFile, "completed", "Build successful!", {
|
||||
fileSize: stats.size,
|
||||
fileName: `${appName || "app"}.apk`
|
||||
});
|
||||
|
||||
// Clean up project dir to save space
|
||||
fs.rmSync(projectDir, { recursive: true, force: true });
|
||||
|
||||
} catch (err) {
|
||||
console.error(`Build ${buildId} failed:`, err.message);
|
||||
updateStatus(statusFile, "failed", err.message || "Build failed");
|
||||
// Clean up
|
||||
if (fs.existsSync(projectDir)) {
|
||||
fs.rmSync(projectDir, { recursive: true, force: true });
|
||||
}
|
||||
} finally {
|
||||
activeBuildIds.delete(buildId);
|
||||
}
|
||||
});
|
||||
|
||||
// Get build status
|
||||
app.get("/build/:buildId/status", (req, res) => {
|
||||
const statusFile = path.join(BUILDS_DIR, `${req.params.buildId}.status.json`);
|
||||
if (!fs.existsSync(statusFile)) {
|
||||
return res.status(404).json({ error: "Build not found" });
|
||||
}
|
||||
res.json(JSON.parse(fs.readFileSync(statusFile, "utf8")));
|
||||
});
|
||||
|
||||
// Download APK
|
||||
app.get("/build/:buildId/download", (req, res) => {
|
||||
const apkPath = path.join(BUILDS_DIR, `${req.params.buildId}.apk`);
|
||||
if (!fs.existsSync(apkPath)) {
|
||||
return res.status(404).json({ error: "APK not found" });
|
||||
}
|
||||
const statusFile = path.join(BUILDS_DIR, `${req.params.buildId}.status.json`);
|
||||
let fileName = "app.apk";
|
||||
if (fs.existsSync(statusFile)) {
|
||||
try {
|
||||
const s = JSON.parse(fs.readFileSync(statusFile, "utf8"));
|
||||
if (s.fileName) fileName = s.fileName;
|
||||
} catch {}
|
||||
}
|
||||
res.download(apkPath, fileName);
|
||||
});
|
||||
|
||||
// Source code ZIP
|
||||
app.post("/source", async (req, res) => {
|
||||
const { files, appName, packageName } = req.body;
|
||||
if (!files) return res.status(400).json({ error: "files required" });
|
||||
|
||||
const zip = new JSZip();
|
||||
const folder = zip.folder(appName || "expo-project");
|
||||
|
||||
for (const [filePath, content] of Object.entries(files)) {
|
||||
folder.file(filePath, content);
|
||||
}
|
||||
|
||||
// Add scaffolding files if not present
|
||||
if (!files["package.json"]) {
|
||||
folder.file("package.json", JSON.stringify({
|
||||
name: (packageName || "apk-forge-app").replace(/[^a-z0-9-]/g, "-"),
|
||||
version: "1.0.0",
|
||||
main: "expo/AppEntry.js",
|
||||
scripts: { start: "expo start", android: "expo start --android" },
|
||||
dependencies: {
|
||||
"expo": "~52.0.0", "react": "18.3.1", "react-native": "0.76.3"
|
||||
}
|
||||
}, null, 2));
|
||||
}
|
||||
if (!files["app.json"]) {
|
||||
const safeName = (appName || "My App").replace(/[^a-zA-Z0-9 ]/g, "");
|
||||
folder.file("app.json", JSON.stringify({
|
||||
expo: { name: safeName, slug: safeName.toLowerCase().replace(/\s+/g, "-"), version: "1.0.0" }
|
||||
}, null, 2));
|
||||
}
|
||||
if (!files["README.md"]) {
|
||||
folder.file("README.md", `# ${appName || "Expo App"}\n\nGenerated by APK Forge.\n\n## Getting Started\n\n\`\`\`bash\nnpm install\nnpx expo start\n\`\`\`\n`);
|
||||
}
|
||||
|
||||
const buffer = await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" });
|
||||
res.set({
|
||||
"Content-Type": "application/zip",
|
||||
"Content-Disposition": `attachment; filename="${appName || "project"}-source.zip"`,
|
||||
"Content-Length": buffer.length
|
||||
});
|
||||
res.send(buffer);
|
||||
});
|
||||
|
||||
function updateStatus(file, status, message, extra = {}) {
|
||||
fs.writeFileSync(file, JSON.stringify({
|
||||
status, message, updatedAt: new Date().toISOString(), ...extra
|
||||
}));
|
||||
}
|
||||
|
||||
// Create a minimal 1x1 PNG placeholder
|
||||
function createPlaceholderPng() {
|
||||
// Minimal valid PNG: 1x1 pixel, RGBA, dark background
|
||||
return Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
|
||||
"base64"
|
||||
);
|
||||
}
|
||||
|
||||
const PORT = process.env.PORT || 3001;
|
||||
app.listen(PORT, "0.0.0.0", () => {
|
||||
console.log(`Build worker running on port ${PORT}`);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "${APP_PORT:-3000}:3000"
|
||||
environment:
|
||||
- MONGODB_URI=${MONGODB_URI}
|
||||
- NEXTAUTH_SECRET=${NEXTAUTH_SECRET}
|
||||
- LLM_API_URL=${LLM_API_URL}
|
||||
- LLM_API_KEY=${LLM_API_KEY}
|
||||
- LLM_MODEL=${LLM_MODEL}
|
||||
- NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL}
|
||||
- BUILD_WORKER_URL=http://build-worker:3001
|
||||
depends_on:
|
||||
- build-worker
|
||||
restart: unless-stopped
|
||||
|
||||
build-worker:
|
||||
build:
|
||||
context: ./build-worker
|
||||
dockerfile: Dockerfile
|
||||
volumes:
|
||||
- build-cache:/app/builds
|
||||
- gradle-cache:/root/.gradle
|
||||
environment:
|
||||
- PORT=3001
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 4G
|
||||
|
||||
volumes:
|
||||
build-cache:
|
||||
gradle-cache:
|
||||
@@ -4,6 +4,8 @@ import { getDb } from "@/lib/db";
|
||||
import { ObjectId } from "mongodb";
|
||||
import JSZip from "jszip";
|
||||
|
||||
const BUILD_WORKER_URL = process.env.BUILD_WORKER_URL || "http://localhost:3001";
|
||||
|
||||
export async function GET(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
@@ -23,16 +25,36 @@ export async function GET(
|
||||
return NextResponse.json({ error: "Build not ready" }, { status: 400 });
|
||||
}
|
||||
|
||||
const files = (build.files || {}) as Record<string, string>;
|
||||
const projectName = (build.projectName as string) || "my-app";
|
||||
const safeName = projectName.replace(/[^a-zA-Z0-9-_]/g, "-");
|
||||
|
||||
// APK builds — proxy download from build worker
|
||||
if (build.type === "apk") {
|
||||
try {
|
||||
const workerRes = await fetch(`${BUILD_WORKER_URL}/build/${id}/download`);
|
||||
if (workerRes.ok && workerRes.body) {
|
||||
const apkBuffer = await workerRes.arrayBuffer();
|
||||
return new NextResponse(apkBuffer, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/vnd.android.package-archive",
|
||||
"Content-Disposition": `attachment; filename="${safeName}.apk"`,
|
||||
"Content-Length": apkBuffer.byteLength.toString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Worker unreachable — fall back to source ZIP
|
||||
}
|
||||
}
|
||||
|
||||
// Source builds or APK fallback — generate ZIP from stored files
|
||||
const files = (build.files || {}) as Record<string, string>;
|
||||
const zip = new JSZip();
|
||||
const dir = zip.folder(safeName)!;
|
||||
for (const [path, content] of Object.entries(files)) {
|
||||
dir.file(path, content);
|
||||
}
|
||||
|
||||
const zipBuffer = await zip.generateAsync({ type: "uint8array" });
|
||||
|
||||
return new NextResponse(zipBuffer as unknown as BodyInit, {
|
||||
|
||||
@@ -3,6 +3,8 @@ import { getSession } from "@/lib/auth";
|
||||
import { getDb } from "@/lib/db";
|
||||
import { ObjectId } from "mongodb";
|
||||
|
||||
const BUILD_WORKER_URL = process.env.BUILD_WORKER_URL || "http://localhost:3001";
|
||||
|
||||
export async function GET(
|
||||
_req: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
@@ -21,5 +23,32 @@ export async function GET(
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// If build is queued/building, check worker for latest status
|
||||
if (build.type === "apk" && (build.status === "queued" || build.status === "building")) {
|
||||
try {
|
||||
const workerRes = await fetch(`${BUILD_WORKER_URL}/build/${id}/status`);
|
||||
if (workerRes.ok) {
|
||||
const workerStatus = await workerRes.json();
|
||||
// Update DB if status changed
|
||||
if (workerStatus.status !== build.status) {
|
||||
const update: Record<string, unknown> = { status: workerStatus.status };
|
||||
if (workerStatus.status === "completed") {
|
||||
update.completedAt = new Date();
|
||||
update.fileSize = workerStatus.fileSize;
|
||||
update.downloadUrl = `/api/build/${id}/download`;
|
||||
} else if (workerStatus.status === "failed") {
|
||||
update.completedAt = new Date();
|
||||
update.errorMessage = workerStatus.message;
|
||||
}
|
||||
await db.collection("builds").updateOne({ _id: new ObjectId(id) }, { $set: update });
|
||||
return NextResponse.json({ build: { ...build, ...update, statusMessage: workerStatus.message } });
|
||||
}
|
||||
return NextResponse.json({ build: { ...build, statusMessage: workerStatus.message } });
|
||||
}
|
||||
} catch {
|
||||
// Worker unreachable — report current DB status
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ build });
|
||||
}
|
||||
+35
-22
@@ -4,6 +4,8 @@ import { getDb } from "@/lib/db";
|
||||
import { ObjectId } from "mongodb";
|
||||
import JSZip from "jszip";
|
||||
|
||||
const BUILD_WORKER_URL = process.env.BUILD_WORKER_URL || "http://localhost:3001";
|
||||
|
||||
function generateZip(projectName: string, currentFiles: Record<string, string>) {
|
||||
const zip = new JSZip();
|
||||
const safeName = projectName.replace(/[^a-zA-Z0-9-_]/g, "-") || "my-app";
|
||||
@@ -77,43 +79,55 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
// Create build record
|
||||
const build = {
|
||||
const buildDoc = {
|
||||
projectId,
|
||||
userId: session.userId,
|
||||
status: "queued" as const,
|
||||
type: "apk" as const,
|
||||
files: currentFiles,
|
||||
projectName,
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
const result = await db.collection("builds").insertOne(build);
|
||||
const result = await db.collection("builds").insertOne(buildDoc);
|
||||
const buildId = result.insertedId.toString();
|
||||
|
||||
// Simulate build process — mark completed with source ZIP
|
||||
const zip = generateZip(projectName, currentFiles);
|
||||
const zipBuffer = await zip.generateAsync({ type: "uint8array" });
|
||||
// Send to build worker (fire and forget — worker updates status)
|
||||
try {
|
||||
const workerRes = await fetch(`${BUILD_WORKER_URL}/build`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
buildId,
|
||||
files: currentFiles,
|
||||
appName: projectName,
|
||||
packageName: `com.apkforge.${projectName.replace(/[^a-zA-Z0-9]/g, "").toLowerCase().slice(0, 30)}`,
|
||||
}),
|
||||
});
|
||||
|
||||
await db.collection("builds").updateOne(
|
||||
{ _id: result.insertedId },
|
||||
{
|
||||
$set: {
|
||||
status: "completed",
|
||||
startedAt: new Date(),
|
||||
completedAt: new Date(),
|
||||
fileSize: zipBuffer.length,
|
||||
downloadUrl: `/api/build/${result.insertedId.toString()}/download`,
|
||||
},
|
||||
if (!workerRes.ok) {
|
||||
throw new Error(`Worker returned ${workerRes.status}`);
|
||||
}
|
||||
);
|
||||
} catch (workerErr) {
|
||||
// Worker unreachable — mark build failed
|
||||
await db.collection("builds").updateOne(
|
||||
{ _id: result.insertedId },
|
||||
{ $set: { status: "failed", errorMessage: "Build worker unavailable. Please try again later.", completedAt: new Date() } }
|
||||
);
|
||||
return NextResponse.json({
|
||||
buildId,
|
||||
status: "failed",
|
||||
error: "Build worker is currently unavailable. You can download the source code instead.",
|
||||
}, { status: 503 });
|
||||
}
|
||||
|
||||
await incrementUsage(session.userId, "buildsThisMonth");
|
||||
await incrementUsage(session.userId, "totalBuilds");
|
||||
|
||||
return NextResponse.json({
|
||||
buildId: result.insertedId.toString(),
|
||||
status: "completed",
|
||||
message: "APK build coming soon — your source code ZIP is ready. Use it to build locally with `npx expo start` or `npx eas build`.",
|
||||
downloadUrl: `/api/build/${result.insertedId.toString()}/download`,
|
||||
buildId,
|
||||
status: "queued",
|
||||
message: "APK build started! This typically takes 3-5 minutes.",
|
||||
statusUrl: `/api/build/${buildId}/status`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -127,7 +141,6 @@ export async function POST(req: NextRequest) {
|
||||
userId: session.userId,
|
||||
status: "completed",
|
||||
type: "source",
|
||||
files: currentFiles,
|
||||
projectName,
|
||||
fileSize: zipBuffer.length,
|
||||
startedAt: new Date(),
|
||||
|
||||
Reference in new issue
Block a user