重构:将 "lobster" 重命名为 "claw" 并添加国际化支持 (i18n)

This commit is contained in:
richarjiang
2026-03-13 12:07:28 +08:00
parent fa4c458eda
commit 9e30771180
38 changed files with 1003 additions and 344 deletions

View File

@@ -1,8 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { eq, desc, sql, and } from "drizzle-orm";
import { db } from "@/lib/db";
import { lobsters, tasks } from "@/lib/db/schema";
import { getActiveLobsterIds } from "@/lib/redis";
import { claws, tasks } from "@/lib/db/schema";
import { getActiveClawIds } from "@/lib/redis";
export async function GET(req: NextRequest) {
try {
@@ -13,29 +13,29 @@ export async function GET(req: NextRequest) {
const conditions = [];
if (region) {
conditions.push(eq(lobsters.region, region));
conditions.push(eq(claws.region, region));
}
const whereClause = conditions.length > 0 ? and(...conditions) : undefined;
const lobsterRows = await db
const clawRows = await db
.select()
.from(lobsters)
.from(claws)
.where(whereClause)
.orderBy(desc(lobsters.lastHeartbeat))
.orderBy(desc(claws.lastHeartbeat))
.limit(limit);
const totalResult = await db
.select({ count: sql<number>`count(*)` })
.from(lobsters)
.from(claws)
.where(whereClause);
const total = totalResult[0]?.count ?? 0;
const activeLobsterIds = await getActiveLobsterIds();
const activeSet = new Set(activeLobsterIds);
const activeClawIds = await getActiveClawIds();
const activeSet = new Set(activeClawIds);
const lobsterList = await Promise.all(
lobsterRows.map(async (lobster) => {
const clawList = await Promise.all(
clawRows.map(async (claw) => {
const latestTaskRows = await db
.select({
summary: tasks.summary,
@@ -43,28 +43,28 @@ export async function GET(req: NextRequest) {
durationMs: tasks.durationMs,
})
.from(tasks)
.where(eq(tasks.lobsterId, lobster.id))
.where(eq(tasks.clawId, claw.id))
.orderBy(desc(tasks.timestamp))
.limit(1);
const lastTask = latestTaskRows[0] ?? null;
return {
id: lobster.id,
name: lobster.name,
model: lobster.model,
platform: lobster.platform,
city: lobster.city,
country: lobster.country,
isOnline: activeSet.has(lobster.id),
id: claw.id,
name: claw.name,
model: claw.model,
platform: claw.platform,
city: claw.city,
country: claw.country,
isOnline: activeSet.has(claw.id),
lastTask,
};
})
);
return NextResponse.json({ lobsters: lobsterList, total });
return NextResponse.json({ claws: clawList, total });
} catch (error) {
console.error("Lobsters error:", error);
console.error("Claws error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }

View File

@@ -1,10 +1,10 @@
import { NextRequest, NextResponse } from "next/server";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db";
import { lobsters, heartbeats } from "@/lib/db/schema";
import { claws, heartbeats } from "@/lib/db/schema";
import {
setLobsterOnline,
updateActiveLobsters,
setClawOnline,
updateActiveClaws,
incrementHourlyActivity,
publishEvent,
} from "@/lib/redis";
@@ -31,8 +31,8 @@ export async function POST(req: NextRequest) {
}
const apiKey = authHeader.slice(7);
const lobster = await validateApiKey(apiKey);
if (!lobster) {
const claw = await validateApiKey(apiKey);
if (!claw) {
return NextResponse.json({ error: "Invalid API key" }, { status: 401 });
}
@@ -61,7 +61,7 @@ export async function POST(req: NextRequest) {
updatedAt: now,
};
if (clientIp !== lobster.ip) {
if (clientIp !== claw.ip) {
const geo = await getGeoLocation(clientIp);
if (geo) {
updateFields.latitude = String(geo.latitude);
@@ -77,27 +77,27 @@ export async function POST(req: NextRequest) {
if (parsed.data.model) updateFields.model = parsed.data.model;
if (parsed.data.platform) updateFields.platform = parsed.data.platform;
await setLobsterOnline(lobster.id, clientIp);
await updateActiveLobsters(lobster.id);
await setClawOnline(claw.id, clientIp);
await updateActiveClaws(claw.id);
await incrementHourlyActivity();
await db
.update(lobsters)
.update(claws)
.set(updateFields)
.where(eq(lobsters.id, lobster.id));
.where(eq(claws.id, claw.id));
// Insert heartbeat record asynchronously
db.insert(heartbeats)
.values({ lobsterId: lobster.id, ip: clientIp, timestamp: now })
.values({ clawId: claw.id, ip: clientIp, timestamp: now })
.then(() => {})
.catch((err: unknown) => console.error("Failed to insert heartbeat:", err));
await publishEvent({
type: "heartbeat",
lobsterId: lobster.id,
lobsterName: (updateFields.name as string) ?? lobster.name,
city: (updateFields.city as string) ?? lobster.city,
country: (updateFields.country as string) ?? lobster.country,
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 });

View File

@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { gte, and, isNotNull, sql } from "drizzle-orm";
import { db } from "@/lib/db";
import { lobsters } from "@/lib/db/schema";
import { claws } from "@/lib/db/schema";
import { getCacheHeatmap, setCacheHeatmap } from "@/lib/redis";
export async function GET() {
@@ -13,34 +13,34 @@ export async function GET() {
const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
const activeLobsters = await db
const activeClaws = await db
.select({
city: lobsters.city,
country: lobsters.country,
latitude: lobsters.latitude,
longitude: lobsters.longitude,
city: claws.city,
country: claws.country,
latitude: claws.latitude,
longitude: claws.longitude,
count: sql<number>`count(*)`,
})
.from(lobsters)
.from(claws)
.where(
and(
gte(lobsters.lastHeartbeat, fiveMinutesAgo),
isNotNull(lobsters.latitude),
isNotNull(lobsters.longitude)
gte(claws.lastHeartbeat, fiveMinutesAgo),
isNotNull(claws.latitude),
isNotNull(claws.longitude)
)
)
.groupBy(
lobsters.city,
lobsters.country,
lobsters.latitude,
lobsters.longitude
claws.city,
claws.country,
claws.latitude,
claws.longitude
);
const points = activeLobsters.map((row) => ({
const points = activeClaws.map((row) => ({
lat: Number(row.latitude),
lng: Number(row.longitude),
weight: row.count,
lobsterCount: row.count,
clawCount: row.count,
city: row.city,
country: row.country,
}));

View File

@@ -1,10 +1,10 @@
import { NextRequest, NextResponse } from "next/server";
import { nanoid } from "nanoid";
import { db } from "@/lib/db";
import { lobsters } from "@/lib/db/schema";
import { claws } from "@/lib/db/schema";
import {
setLobsterOnline,
updateActiveLobsters,
setClawOnline,
updateActiveClaws,
incrementGlobalStat,
incrementRegionCount,
publishEvent,
@@ -33,14 +33,14 @@ export async function POST(req: NextRequest) {
}
const { name, model, platform } = parsed.data;
const lobsterId = nanoid(21);
const clawId = nanoid(21);
const apiKey = generateApiKey();
const clientIp = getClientIp(req);
const geo = await getGeoLocation(clientIp);
const now = new Date();
await db.insert(lobsters).values({
id: lobsterId,
await db.insert(claws).values({
id: clawId,
apiKey,
name,
model: model ?? null,
@@ -58,9 +58,9 @@ export async function POST(req: NextRequest) {
updatedAt: now,
});
await setLobsterOnline(lobsterId, clientIp);
await updateActiveLobsters(lobsterId);
await incrementGlobalStat("total_lobsters");
await setClawOnline(clawId, clientIp);
await updateActiveClaws(clawId);
await incrementGlobalStat("total_claws");
if (geo?.region) {
await incrementRegionCount(geo.region);
@@ -68,14 +68,14 @@ export async function POST(req: NextRequest) {
await publishEvent({
type: "online",
lobsterId,
lobsterName: name,
clawId,
clawName: name,
city: geo?.city ?? null,
country: geo?.country ?? null,
});
return NextResponse.json({
lobsterId,
clawId,
apiKey,
endpoint: `${process.env.NEXT_PUBLIC_APP_URL}/api/v1`,
});

View File

@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { gte, sql } from "drizzle-orm";
import { db } from "@/lib/db";
import { lobsters, tasks } from "@/lib/db/schema";
import { claws, tasks } from "@/lib/db/schema";
import {
redis,
getGlobalStats,
@@ -23,16 +23,16 @@ export async function GET() {
const now = Date.now();
const fiveMinutesAgo = now - 300_000;
const activeLobsters = await redis.zcount(
"active:lobsters",
const activeClaws = await redis.zcount(
"active:claws",
fiveMinutesAgo,
"+inf"
);
const totalLobstersResult = await db
const totalClawsResult = await db
.select({ count: sql<number>`count(*)` })
.from(lobsters);
const totalLobsters = totalLobstersResult[0]?.count ?? 0;
.from(claws);
const totalClaws = totalClawsResult[0]?.count ?? 0;
const todayStart = new Date();
todayStart.setHours(0, 0, 0, 0);
@@ -58,8 +58,8 @@ export async function GET() {
}
return NextResponse.json({
totalLobsters,
activeLobsters,
totalClaws,
activeClaws,
tasksToday,
tasksTotal: parseInt(globalStats.total_tasks ?? "0", 10),
avgTaskDuration,

View File

@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { eq, sql } from "drizzle-orm";
import { db } from "@/lib/db";
import { lobsters, tasks } from "@/lib/db/schema";
import { claws, tasks } from "@/lib/db/schema";
import {
incrementGlobalStat,
incrementHourlyActivity,
@@ -21,8 +21,8 @@ export async function POST(req: NextRequest) {
}
const apiKey = authHeader.slice(7);
const lobster = await validateApiKey(apiKey);
if (!lobster) {
const claw = await validateApiKey(apiKey);
if (!claw) {
return NextResponse.json({ error: "Invalid API key" }, { status: 401 });
}
@@ -39,7 +39,7 @@ export async function POST(req: NextRequest) {
const now = new Date();
const insertResult = await db.insert(tasks).values({
lobsterId: lobster.id,
clawId: claw.id,
summary,
durationMs,
model: model ?? null,
@@ -48,9 +48,9 @@ export async function POST(req: NextRequest) {
});
await db
.update(lobsters)
.set({ totalTasks: sql`${lobsters.totalTasks} + 1`, updatedAt: now })
.where(eq(lobsters.id, lobster.id));
.update(claws)
.set({ totalTasks: sql`${claws.totalTasks} + 1`, updatedAt: now })
.where(eq(claws.id, claw.id));
await incrementGlobalStat("total_tasks");
await incrementGlobalStat("tasks_today");
@@ -58,10 +58,10 @@ export async function POST(req: NextRequest) {
await publishEvent({
type: "task",
lobsterId: lobster.id,
lobsterName: lobster.name,
city: lobster.city,
country: lobster.country,
clawId: claw.id,
clawName: claw.name,
city: claw.city,
country: claw.country,
summary,
durationMs,
});