2026-04-22 19:00:15 +08:00
|
|
|
import { randomUUID } from "node:crypto";
|
2026-05-13 19:01:30 +08:00
|
|
|
import cookie from "@fastify/cookie";
|
2026-04-14 22:01:04 +08:00
|
|
|
import cors from "@fastify/cors";
|
|
|
|
|
import rateLimit from "@fastify/rate-limit";
|
2026-04-30 18:49:52 +08:00
|
|
|
import { getDispatcherStatus, initDispatcher, isGpuAvailable } from "@snapotter/ai";
|
2026-04-24 18:02:21 +08:00
|
|
|
import { APP_VERSION } from "@snapotter/shared";
|
2026-04-22 19:00:15 +08:00
|
|
|
import { eq } from "drizzle-orm";
|
2026-03-25 09:24:37 +08:00
|
|
|
import Fastify from "fastify";
|
|
|
|
|
import { env } from "./config.js";
|
|
|
|
|
import { db, schema } from "./db/index.js";
|
2026-03-22 02:51:57 +08:00
|
|
|
import { runMigrations } from "./db/migrate.js";
|
2026-04-23 21:45:10 +08:00
|
|
|
import { captureException, initAnalytics, shutdownAnalytics } from "./lib/analytics.js";
|
2026-03-22 03:09:33 +08:00
|
|
|
import { startCleanupCron } from "./lib/cleanup.js";
|
2026-05-05 17:16:19 +08:00
|
|
|
import { buildCsp } from "./lib/csp.js";
|
2026-04-18 02:34:21 +08:00
|
|
|
import { ensureAiDirs, recoverInterruptedInstalls } from "./lib/feature-status.js";
|
2026-03-29 17:23:41 +08:00
|
|
|
import { shutdownWorkerPool } from "./lib/worker-pool.js";
|
2026-04-22 18:10:04 +08:00
|
|
|
import { requirePermission } from "./permissions.js";
|
2026-05-16 12:36:06 +08:00
|
|
|
import {
|
|
|
|
|
authMiddleware,
|
|
|
|
|
authRoutes,
|
|
|
|
|
ensureAnonymousUser,
|
|
|
|
|
ensureDefaultAdmin,
|
|
|
|
|
} from "./plugins/auth.js";
|
2026-05-13 19:01:30 +08:00
|
|
|
import { oidcRoutes } from "./plugins/oidc.js";
|
2026-03-25 09:24:37 +08:00
|
|
|
import { registerStatic } from "./plugins/static.js";
|
|
|
|
|
import { registerUpload } from "./plugins/upload.js";
|
2026-04-22 19:03:23 +08:00
|
|
|
import { analyticsRoutes } from "./routes/analytics.js";
|
2026-03-25 09:24:37 +08:00
|
|
|
import { apiKeyRoutes } from "./routes/api-keys.js";
|
2026-04-22 18:10:04 +08:00
|
|
|
import { auditLogRoutes } from "./routes/audit-log.js";
|
2026-03-22 04:03:38 +08:00
|
|
|
import { registerBatchRoutes } from "./routes/batch.js";
|
2026-05-15 17:02:49 +08:00
|
|
|
import { configRoutes } from "./routes/config.js";
|
2026-03-27 12:28:35 +08:00
|
|
|
import { docsRoutes } from "./routes/docs.js";
|
2026-04-18 02:34:21 +08:00
|
|
|
import { registerFeatureRoutes } from "./routes/features.js";
|
2026-05-11 21:24:56 +08:00
|
|
|
import { registerFetchUrlsRoute } from "./routes/fetch-urls.js";
|
2026-03-25 09:24:37 +08:00
|
|
|
import { fileRoutes } from "./routes/files.js";
|
2026-05-08 16:05:17 +08:00
|
|
|
import { registerMemeTemplates } from "./routes/meme-templates.js";
|
2026-03-22 04:41:51 +08:00
|
|
|
import { registerPipelineRoutes } from "./routes/pipeline.js";
|
2026-03-29 17:23:41 +08:00
|
|
|
import { recoverStaleJobs, registerProgressRoutes } from "./routes/progress.js";
|
2026-04-22 18:10:04 +08:00
|
|
|
import { rolesRoutes } from "./routes/roles.js";
|
2026-03-22 19:28:57 +08:00
|
|
|
import { settingsRoutes } from "./routes/settings.js";
|
2026-03-25 09:24:37 +08:00
|
|
|
import { teamsRoutes } from "./routes/teams.js";
|
|
|
|
|
import { registerToolRoutes } from "./routes/tools/index.js";
|
2026-03-25 01:16:52 +08:00
|
|
|
import { userFileRoutes } from "./routes/user-files.js";
|
2026-03-22 02:51:57 +08:00
|
|
|
|
|
|
|
|
// Run before anything else
|
|
|
|
|
runMigrations();
|
|
|
|
|
console.log("Database initialized");
|
2026-03-22 02:46:34 +08:00
|
|
|
|
2026-04-23 14:45:04 +08:00
|
|
|
if (env.AUTH_ENABLED) {
|
|
|
|
|
await ensureDefaultAdmin();
|
2026-05-16 12:36:06 +08:00
|
|
|
} else {
|
|
|
|
|
ensureAnonymousUser();
|
2026-04-23 14:45:04 +08:00
|
|
|
}
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-04-22 19:00:15 +08:00
|
|
|
function ensureInstanceId() {
|
|
|
|
|
const existing = db
|
|
|
|
|
.select()
|
|
|
|
|
.from(schema.settings)
|
|
|
|
|
.where(eq(schema.settings.key, "instance_id"))
|
|
|
|
|
.get();
|
|
|
|
|
if (!existing) {
|
|
|
|
|
db.insert(schema.settings).values({ key: "instance_id", value: randomUUID() }).run();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ensureInstanceId();
|
2026-04-25 22:39:18 +08:00
|
|
|
|
|
|
|
|
function ensureDefaultSettings() {
|
|
|
|
|
const defaults: Record<string, string> = {
|
|
|
|
|
defaultTheme: env.DEFAULT_THEME,
|
|
|
|
|
defaultLocale: env.DEFAULT_LOCALE,
|
2026-05-16 11:37:28 +08:00
|
|
|
defaultToolView: env.DEFAULT_TOOL_VIEW,
|
2026-04-25 22:39:18 +08:00
|
|
|
};
|
|
|
|
|
for (const [key, value] of Object.entries(defaults)) {
|
|
|
|
|
const existing = db.select().from(schema.settings).where(eq(schema.settings.key, key)).get();
|
|
|
|
|
if (!existing) {
|
|
|
|
|
db.insert(schema.settings).values({ key, value }).run();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ensureDefaultSettings();
|
2026-05-13 19:01:30 +08:00
|
|
|
|
|
|
|
|
if (!env.COOKIE_SECRET) {
|
|
|
|
|
const existing = db
|
|
|
|
|
.select()
|
|
|
|
|
.from(schema.settings)
|
|
|
|
|
.where(eq(schema.settings.key, "cookie_secret"))
|
|
|
|
|
.get();
|
|
|
|
|
if (existing) {
|
|
|
|
|
(env as Record<string, unknown>).COOKIE_SECRET = existing.value;
|
|
|
|
|
} else {
|
|
|
|
|
const generated = randomUUID() + randomUUID();
|
|
|
|
|
db.insert(schema.settings).values({ key: "cookie_secret", value: generated }).run();
|
|
|
|
|
(env as Record<string, unknown>).COOKIE_SECRET = generated;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 21:45:10 +08:00
|
|
|
await initAnalytics();
|
2026-04-22 19:00:15 +08:00
|
|
|
|
2026-06-06 20:17:49 +08:00
|
|
|
// Enterprise features (license-gated)
|
|
|
|
|
let enterpriseLicense: { org: string; plan: string } | null = null;
|
|
|
|
|
try {
|
|
|
|
|
const { initEnterprise } = await import("@snapotter/enterprise");
|
|
|
|
|
const result = initEnterprise(env.SNAPOTTER_LICENSE_KEY || undefined);
|
|
|
|
|
if (result.valid && result.license) {
|
|
|
|
|
enterpriseLicense = result.license;
|
|
|
|
|
} else if (env.SNAPOTTER_LICENSE_KEY) {
|
|
|
|
|
console.warn("[WARN] Invalid or expired enterprise license key");
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// Enterprise package not available
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-29 17:23:41 +08:00
|
|
|
// Mark any jobs left in processing/queued from a previous unclean shutdown
|
|
|
|
|
recoverStaleJobs();
|
|
|
|
|
|
2026-04-18 02:34:21 +08:00
|
|
|
// Set up AI feature directories and recover from interrupted installs
|
|
|
|
|
ensureAiDirs();
|
|
|
|
|
recoverInterruptedInstalls();
|
|
|
|
|
|
2026-03-22 02:46:34 +08:00
|
|
|
const app = Fastify({
|
2026-04-11 14:47:30 +08:00
|
|
|
logger: { level: env.LOG_LEVEL },
|
2026-04-20 21:50:17 +08:00
|
|
|
bodyLimit: env.MAX_UPLOAD_SIZE_MB > 0 ? env.MAX_UPLOAD_SIZE_MB * 1024 * 1024 : 1073741824,
|
2026-04-21 10:19:08 +08:00
|
|
|
trustProxy: env.TRUST_PROXY,
|
|
|
|
|
routerOptions: { maxParamLength: 500 },
|
2026-03-22 02:46:34 +08:00
|
|
|
});
|
|
|
|
|
|
2026-05-13 14:19:51 +08:00
|
|
|
// Image processing (especially AI batch) can run for tens of minutes.
|
|
|
|
|
// Node.js defaults to a 5-minute requestTimeout which kills long-running
|
|
|
|
|
// connections. Set a generous default; per-route overrides disable it entirely.
|
|
|
|
|
app.server.requestTimeout = 30 * 60 * 1000;
|
|
|
|
|
app.server.headersTimeout = 60 * 1000;
|
|
|
|
|
|
2026-05-01 18:11:49 +08:00
|
|
|
app.removeContentTypeParser("application/json");
|
|
|
|
|
app.addContentTypeParser("application/json", { parseAs: "string" }, (_request, body, done) => {
|
|
|
|
|
try {
|
|
|
|
|
const str = typeof body === "string" ? body : (body as Buffer).toString();
|
|
|
|
|
done(null, str.length > 0 ? JSON.parse(str) : {});
|
2026-06-07 21:54:27 +08:00
|
|
|
} catch {
|
|
|
|
|
const parseErr = new Error("Malformed JSON in request body") as Error & { statusCode: number };
|
|
|
|
|
parseErr.statusCode = 400;
|
|
|
|
|
done(parseErr, undefined);
|
2026-05-01 18:11:49 +08:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-17 14:15:27 +08:00
|
|
|
app.setErrorHandler((error: Error & { statusCode?: number }, request, reply) => {
|
|
|
|
|
const statusCode = error.statusCode ?? 500;
|
2026-06-07 10:43:52 +08:00
|
|
|
if (statusCode === 429) {
|
|
|
|
|
request.log.warn({ url: request.url, method: request.method }, "Rate limit exceeded");
|
|
|
|
|
} else if (statusCode >= 500) {
|
|
|
|
|
request.log.error(
|
|
|
|
|
{ err: error, url: request.url, method: request.method },
|
|
|
|
|
"Unhandled request error",
|
|
|
|
|
);
|
2026-05-01 19:01:05 +08:00
|
|
|
captureException(error, request);
|
2026-06-07 10:43:52 +08:00
|
|
|
} else {
|
|
|
|
|
request.log.warn({ err: error, url: request.url, method: request.method }, "Request error");
|
2026-05-01 19:01:05 +08:00
|
|
|
}
|
2026-04-17 14:15:27 +08:00
|
|
|
reply.status(statusCode).send({
|
|
|
|
|
error: statusCode >= 500 ? "Internal server error" : error.message,
|
2026-04-21 10:19:08 +08:00
|
|
|
...(statusCode < 500 && { details: error.message }),
|
2026-04-17 14:15:27 +08:00
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-22 02:46:34 +08:00
|
|
|
// Plugins
|
2026-03-23 11:46:45 +08:00
|
|
|
await app.register(cors, {
|
|
|
|
|
origin: env.CORS_ORIGIN
|
|
|
|
|
? env.CORS_ORIGIN.split(",").map((s) => s.trim())
|
2026-03-25 09:24:37 +08:00
|
|
|
: process.env.NODE_ENV !== "production",
|
2026-03-23 11:46:45 +08:00
|
|
|
});
|
|
|
|
|
|
2026-05-13 21:33:50 +08:00
|
|
|
// Security headers -- applied in all environments. HSTS is ignored over plain
|
|
|
|
|
// HTTP so it is safe (and desirable) to send it in dev/staging too. CSP catches
|
|
|
|
|
// injection issues early when applied during development.
|
2026-03-23 11:46:45 +08:00
|
|
|
app.addHook("onSend", async (_request, reply) => {
|
|
|
|
|
reply.header("X-Content-Type-Options", "nosniff");
|
|
|
|
|
reply.header("X-Frame-Options", "DENY");
|
|
|
|
|
reply.header("X-XSS-Protection", "0");
|
|
|
|
|
reply.header("Referrer-Policy", "strict-origin-when-cross-origin");
|
2026-03-24 21:38:06 +08:00
|
|
|
reply.header("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
|
2026-05-13 21:33:50 +08:00
|
|
|
reply.header("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
|
|
|
|
|
reply.header("Content-Security-Policy", buildCsp(_request.url.startsWith("/api/docs")));
|
2026-03-23 11:46:45 +08:00
|
|
|
});
|
|
|
|
|
|
2026-04-21 10:19:08 +08:00
|
|
|
// Always register rate-limit plugin so per-route limits (login brute-force protection) work.
|
|
|
|
|
await app.register(rateLimit, {
|
2026-06-07 10:43:52 +08:00
|
|
|
max: env.RATE_LIMIT_PER_MIN,
|
2026-04-21 10:19:08 +08:00
|
|
|
timeWindow: "1 minute",
|
|
|
|
|
allowList: (request) => !request.url.startsWith("/api/"),
|
|
|
|
|
});
|
2026-03-22 02:46:34 +08:00
|
|
|
|
2026-06-07 21:54:27 +08:00
|
|
|
// Block TRACE method (returns 401 instead of 405 without this)
|
|
|
|
|
app.addHook("onRequest", async (request, reply) => {
|
|
|
|
|
if (request.method === "TRACE") {
|
|
|
|
|
return reply.status(405).send({ error: "Method not allowed" });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-22 03:47:54 +08:00
|
|
|
// Multipart upload support
|
|
|
|
|
await registerUpload(app);
|
|
|
|
|
|
2026-05-13 19:01:30 +08:00
|
|
|
// Cookie support (required for OIDC state and session cookies)
|
|
|
|
|
await app.register(cookie, {
|
|
|
|
|
secret: env.COOKIE_SECRET,
|
|
|
|
|
hook: "onRequest",
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-15 17:02:49 +08:00
|
|
|
// Public config routes (no auth required)
|
|
|
|
|
await configRoutes(app);
|
|
|
|
|
|
2026-03-22 02:55:10 +08:00
|
|
|
// Auth middleware (must be registered before routes it protects)
|
|
|
|
|
await authMiddleware(app);
|
|
|
|
|
|
|
|
|
|
// Auth routes
|
|
|
|
|
await authRoutes(app);
|
|
|
|
|
|
2026-05-13 19:01:30 +08:00
|
|
|
// OIDC routes
|
|
|
|
|
await oidcRoutes(app);
|
|
|
|
|
|
2026-03-22 03:47:54 +08:00
|
|
|
// File upload/download routes
|
|
|
|
|
await fileRoutes(app);
|
|
|
|
|
|
2026-03-25 01:16:52 +08:00
|
|
|
// User file library routes (persistent file management with versioning)
|
|
|
|
|
await userFileRoutes(app);
|
|
|
|
|
|
2026-05-08 16:05:17 +08:00
|
|
|
// Meme template listing and static serving (before tool routes which have catch-all)
|
|
|
|
|
await registerMemeTemplates(app);
|
|
|
|
|
|
2026-03-22 03:48:11 +08:00
|
|
|
// Tool routes (generic factory-based)
|
|
|
|
|
await registerToolRoutes(app);
|
|
|
|
|
|
2026-03-22 04:03:38 +08:00
|
|
|
// Batch processing routes (must be after tool routes so the registry is populated)
|
|
|
|
|
await registerBatchRoutes(app);
|
|
|
|
|
|
2026-05-11 21:24:56 +08:00
|
|
|
// URL fetch routes (server-side image fetching with SSRF protection)
|
|
|
|
|
await registerFetchUrlsRoute(app);
|
|
|
|
|
|
2026-03-22 04:41:51 +08:00
|
|
|
// Pipeline routes (must be after tool routes so the registry is populated)
|
|
|
|
|
await registerPipelineRoutes(app);
|
|
|
|
|
|
2026-03-22 04:03:38 +08:00
|
|
|
// Progress SSE routes
|
|
|
|
|
await registerProgressRoutes(app);
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
// API key management routes
|
|
|
|
|
await apiKeyRoutes(app);
|
|
|
|
|
|
|
|
|
|
// Settings routes
|
|
|
|
|
await settingsRoutes(app);
|
|
|
|
|
|
2026-04-22 19:03:23 +08:00
|
|
|
// Analytics config and consent routes
|
|
|
|
|
await analyticsRoutes(app);
|
|
|
|
|
|
2026-04-18 02:34:21 +08:00
|
|
|
// Feature management routes (AI feature bundle install/uninstall)
|
|
|
|
|
await registerFeatureRoutes(app);
|
|
|
|
|
|
2026-03-25 09:24:37 +08:00
|
|
|
// Teams routes
|
|
|
|
|
await teamsRoutes(app);
|
|
|
|
|
|
2026-04-22 18:10:04 +08:00
|
|
|
// Audit log routes
|
|
|
|
|
await auditLogRoutes(app);
|
|
|
|
|
|
|
|
|
|
// Roles management routes
|
|
|
|
|
await rolesRoutes(app);
|
|
|
|
|
|
2026-03-27 12:28:35 +08:00
|
|
|
// API docs (Scalar)
|
|
|
|
|
await docsRoutes(app);
|
|
|
|
|
|
2026-04-10 13:21:06 +08:00
|
|
|
// Public health check (checks core dependencies)
|
|
|
|
|
app.get("/api/v1/health", async (_request, reply) => {
|
|
|
|
|
let dbOk = false;
|
|
|
|
|
try {
|
|
|
|
|
db.select().from(schema.settings).limit(1).get();
|
|
|
|
|
dbOk = true;
|
|
|
|
|
} catch {
|
|
|
|
|
/* db unreachable */
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const status = dbOk ? "healthy" : "unhealthy";
|
|
|
|
|
const code = dbOk ? 200 : 503;
|
|
|
|
|
return reply.code(code).send({
|
|
|
|
|
status,
|
|
|
|
|
version: APP_VERSION,
|
|
|
|
|
});
|
|
|
|
|
});
|
2026-03-28 19:00:50 +08:00
|
|
|
|
|
|
|
|
// Admin health check (full diagnostics)
|
|
|
|
|
app.get("/api/v1/admin/health", async (request, reply) => {
|
2026-04-22 18:10:04 +08:00
|
|
|
const admin = requirePermission("system:health")(request, reply);
|
2026-03-28 19:00:50 +08:00
|
|
|
if (!admin) return;
|
|
|
|
|
|
2026-03-23 11:46:45 +08:00
|
|
|
let dbOk = false;
|
|
|
|
|
try {
|
|
|
|
|
db.select().from(schema.settings).limit(1).all();
|
|
|
|
|
dbOk = true;
|
2026-03-25 09:24:37 +08:00
|
|
|
} catch {
|
|
|
|
|
/* db unreachable */
|
|
|
|
|
}
|
2026-03-23 11:46:45 +08:00
|
|
|
return {
|
|
|
|
|
status: dbOk ? "healthy" : "degraded",
|
|
|
|
|
version: APP_VERSION,
|
2026-03-25 09:24:37 +08:00
|
|
|
uptime: `${process.uptime().toFixed(0)}s`,
|
2026-03-23 11:46:45 +08:00
|
|
|
storage: { mode: env.STORAGE_MODE, available: "N/A" },
|
|
|
|
|
database: dbOk ? "ok" : "error",
|
|
|
|
|
queue: { active: 0, pending: 0 },
|
2026-04-26 03:22:26 +08:00
|
|
|
ai: { gpu: isGpuAvailable(), dispatcher: getDispatcherStatus() },
|
2026-06-06 20:17:49 +08:00
|
|
|
enterprise: enterpriseLicense
|
|
|
|
|
? { active: true, org: enterpriseLicense.org, plan: enterpriseLicense.plan }
|
|
|
|
|
: { active: false },
|
2026-03-23 11:46:45 +08:00
|
|
|
};
|
|
|
|
|
});
|
2026-03-22 02:46:34 +08:00
|
|
|
|
2026-03-22 11:04:20 +08:00
|
|
|
// Public config endpoint (for frontend to know if auth is required)
|
2026-05-13 19:01:30 +08:00
|
|
|
app.get("/api/v1/config/auth", async () => {
|
|
|
|
|
const config: Record<string, unknown> = {
|
|
|
|
|
authEnabled: env.AUTH_ENABLED,
|
|
|
|
|
};
|
|
|
|
|
if (env.OIDC_ENABLED) {
|
|
|
|
|
config.oidcEnabled = true;
|
|
|
|
|
config.oidcProviderName = env.OIDC_PROVIDER_NAME || null;
|
|
|
|
|
config.oidcLoginUrl = "/api/auth/oidc/login";
|
|
|
|
|
}
|
|
|
|
|
return config;
|
|
|
|
|
});
|
2026-03-22 11:04:20 +08:00
|
|
|
|
2026-03-22 03:09:33 +08:00
|
|
|
// Serve SPA in production
|
|
|
|
|
if (process.env.NODE_ENV === "production") {
|
|
|
|
|
await registerStatic(app);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Start workspace cleanup cron
|
2026-03-29 17:23:41 +08:00
|
|
|
const cleanupCron = startCleanupCron();
|
2026-03-22 03:09:33 +08:00
|
|
|
|
2026-03-22 02:46:34 +08:00
|
|
|
// Start
|
|
|
|
|
try {
|
|
|
|
|
await app.listen({ port: env.PORT, host: "0.0.0.0" });
|
2026-04-30 18:49:52 +08:00
|
|
|
|
|
|
|
|
const dispatcherResult = await initDispatcher();
|
|
|
|
|
const gpuLine = dispatcherResult.ready
|
|
|
|
|
? dispatcherResult.gpu
|
|
|
|
|
? "[INFO] GPU detected -- AI tools will use CUDA acceleration"
|
|
|
|
|
: "[WARN] No GPU detected -- AI tools will use CPU (slower)"
|
|
|
|
|
: "[WARN] AI sidecar did not start -- AI tools will use per-request Python (slower)";
|
2026-04-21 10:19:08 +08:00
|
|
|
console.log(
|
|
|
|
|
[
|
2026-04-24 18:02:21 +08:00
|
|
|
`SnapOtter v${APP_VERSION} running on port ${env.PORT}`,
|
2026-04-27 01:13:32 +08:00
|
|
|
gpuLine,
|
2026-04-21 10:19:08 +08:00
|
|
|
`[INFO] Rate limit: ${env.RATE_LIMIT_PER_MIN > 0 ? `${env.RATE_LIMIT_PER_MIN}/min` : "disabled"}`,
|
|
|
|
|
`[INFO] Upload limit: ${env.MAX_UPLOAD_SIZE_MB > 0 ? `${env.MAX_UPLOAD_SIZE_MB} MB` : "unlimited"}`,
|
|
|
|
|
`[INFO] Trust proxy: ${env.TRUST_PROXY}`,
|
2026-06-06 20:17:49 +08:00
|
|
|
`[INFO] Storage: ${env.STORAGE_MODE}${env.STORAGE_MODE === "s3" ? ` (${env.S3_BUCKET})` : ""}`,
|
|
|
|
|
enterpriseLicense
|
|
|
|
|
? `[INFO] Enterprise license: ${enterpriseLicense.org} (${enterpriseLicense.plan})`
|
|
|
|
|
: "[INFO] Edition: Community",
|
2026-04-21 10:19:08 +08:00
|
|
|
].join("\n"),
|
|
|
|
|
);
|
2026-03-22 02:46:34 +08:00
|
|
|
} catch (err) {
|
|
|
|
|
app.log.error(err);
|
|
|
|
|
process.exit(1);
|
|
|
|
|
}
|
2026-03-29 17:23:41 +08:00
|
|
|
|
|
|
|
|
// Graceful shutdown
|
2026-04-20 21:50:17 +08:00
|
|
|
const SHUTDOWN_TIMEOUT_MS = 30000;
|
2026-03-29 17:23:41 +08:00
|
|
|
let shuttingDown = false;
|
|
|
|
|
async function shutdown(signal: string) {
|
|
|
|
|
if (shuttingDown) return;
|
|
|
|
|
shuttingDown = true;
|
|
|
|
|
console.log(`\n${signal} received, shutting down gracefully...`);
|
|
|
|
|
|
2026-04-10 13:21:06 +08:00
|
|
|
const forceExit = setTimeout(() => {
|
|
|
|
|
console.error("Shutdown timed out, forcing exit");
|
|
|
|
|
process.exit(1);
|
|
|
|
|
}, SHUTDOWN_TIMEOUT_MS);
|
|
|
|
|
forceExit.unref();
|
|
|
|
|
|
2026-03-29 17:23:41 +08:00
|
|
|
cleanupCron.stop();
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await app.close();
|
|
|
|
|
console.log("HTTP server closed");
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error("Error closing HTTP server:", err);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await shutdownWorkerPool();
|
|
|
|
|
console.log("Worker pool shut down");
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error("Error shutting down worker pool:", err);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
2026-04-24 18:02:21 +08:00
|
|
|
const { shutdownDispatcher } = await import("@snapotter/ai");
|
2026-03-29 17:23:41 +08:00
|
|
|
shutdownDispatcher();
|
|
|
|
|
console.log("Python dispatcher shut down");
|
|
|
|
|
} catch {
|
|
|
|
|
// AI package may not be available
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-06 20:53:39 +08:00
|
|
|
try {
|
|
|
|
|
const { shutdownBrowser } = await import("./lib/browser-service.js");
|
|
|
|
|
await shutdownBrowser();
|
|
|
|
|
console.log("Browser service shut down");
|
|
|
|
|
} catch {
|
|
|
|
|
// Browser service may not have been initialized
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-22 19:03:23 +08:00
|
|
|
try {
|
|
|
|
|
await shutdownAnalytics();
|
|
|
|
|
console.log("Analytics flushed");
|
|
|
|
|
} catch {
|
|
|
|
|
// analytics shutdown is best-effort
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-29 17:23:41 +08:00
|
|
|
try {
|
|
|
|
|
const { sqlite: sqliteConn } = await import("./db/index.js");
|
|
|
|
|
sqliteConn.close();
|
|
|
|
|
console.log("Database connection closed");
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error("Error closing database:", err);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-10 13:21:06 +08:00
|
|
|
clearTimeout(forceExit);
|
2026-03-29 17:23:41 +08:00
|
|
|
process.exit(0);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
|
|
|
process.on("SIGINT", () => shutdown("SIGINT"));
|