104 lines
3.0 KiB
TypeScript
104 lines
3.0 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { eq } from "drizzle-orm";
|
|
import { db } from "@/lib/db";
|
|
import { claws, heartbeats } from "@/lib/db/schema";
|
|
import {
|
|
setClawOnline,
|
|
updateActiveClaws,
|
|
incrementHourlyActivity,
|
|
publishEvent,
|
|
} from "@/lib/redis";
|
|
import { authenticateRequest } from "@/lib/auth/request";
|
|
import { getGeoLocation } from "@/lib/geo/ip-location";
|
|
import { heartbeatSchema } from "@/lib/validators/schemas";
|
|
|
|
function getClientIp(req: NextRequest): string {
|
|
const forwarded = req.headers.get("x-forwarded-for");
|
|
if (forwarded) return forwarded.split(",")[0].trim();
|
|
const realIp = req.headers.get("x-real-ip");
|
|
if (realIp) return realIp.trim();
|
|
return "127.0.0.1";
|
|
}
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const auth = await authenticateRequest(req);
|
|
if (auth instanceof NextResponse) {
|
|
return auth;
|
|
}
|
|
const { claw } = auth;
|
|
|
|
let bodyData = {};
|
|
try {
|
|
const rawBody = await req.text();
|
|
if (rawBody) bodyData = JSON.parse(rawBody);
|
|
} catch {
|
|
// Empty body is fine for heartbeat
|
|
}
|
|
|
|
const parsed = heartbeatSchema.safeParse(bodyData);
|
|
if (!parsed.success) {
|
|
return NextResponse.json(
|
|
{ error: "Validation failed", details: parsed.error.flatten() },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const clientIp = getClientIp(req);
|
|
const now = new Date();
|
|
|
|
const updateFields: Record<string, unknown> = {
|
|
lastHeartbeat: now,
|
|
ip: clientIp,
|
|
updatedAt: now,
|
|
};
|
|
|
|
if (clientIp !== claw.ip) {
|
|
const geo = await getGeoLocation(clientIp);
|
|
if (geo) {
|
|
updateFields.latitude = String(geo.latitude);
|
|
updateFields.longitude = String(geo.longitude);
|
|
updateFields.city = geo.city;
|
|
updateFields.country = geo.country;
|
|
updateFields.countryCode = geo.countryCode;
|
|
updateFields.region = geo.region;
|
|
}
|
|
}
|
|
|
|
if (parsed.data.name) updateFields.name = parsed.data.name;
|
|
if (parsed.data.model) updateFields.model = parsed.data.model;
|
|
if (parsed.data.platform) updateFields.platform = parsed.data.platform;
|
|
|
|
await setClawOnline(claw.id, clientIp);
|
|
await updateActiveClaws(claw.id);
|
|
await incrementHourlyActivity();
|
|
|
|
await db
|
|
.update(claws)
|
|
.set(updateFields)
|
|
.where(eq(claws.id, claw.id));
|
|
|
|
// Insert heartbeat record asynchronously
|
|
db.insert(heartbeats)
|
|
.values({ clawId: claw.id, ip: clientIp, timestamp: now })
|
|
.then(() => {})
|
|
.catch((err: unknown) => console.error("Failed to insert heartbeat:", err));
|
|
|
|
await publishEvent({
|
|
type: "heartbeat",
|
|
clawId: claw.id,
|
|
clawName: (updateFields.name as string) ?? claw.name,
|
|
city: (updateFields.city as string) ?? claw.city,
|
|
country: (updateFields.country as string) ?? claw.country,
|
|
});
|
|
|
|
return NextResponse.json({ ok: true, nextIn: 180 });
|
|
} catch (error) {
|
|
console.error("Heartbeat error:", error);
|
|
return NextResponse.json(
|
|
{ error: "Internal server error" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|