feat: add token usage tracking and leaderboard

- Add token_usage table with composite unique index for claw_id + date
- Add API endpoints: POST /token, GET /token/leaderboard, GET /token/stats
- Add TokenLeaderboard component with daily/total period toggle
- Add CLI commands: `token` and `stats` for reporting and viewing usage
- Add Redis caching for leaderboard with 1-minute TTL
- Add shared utilities: authenticateRequest, getTodayDateString
- Use UPSERT pattern for atomic token updates
- Add i18n translations (en/zh) for new UI elements
This commit is contained in:
richarjiang
2026-03-15 15:17:10 +08:00
parent 8d094ad5cc
commit 36f10954cf
22 changed files with 3140 additions and 11 deletions

View File

@@ -7,6 +7,7 @@ import {
datetime,
json,
index,
uniqueIndex,
} from "drizzle-orm/mysql-core";
import { sql } from "drizzle-orm";
@@ -70,3 +71,21 @@ export const geoCache = mysqlTable("geo_cache", {
region: varchar("region", { length: 50 }),
updatedAt: datetime("updated_at").default(sql`NOW()`),
});
export const tokenUsage = mysqlTable(
"token_usage",
{
id: bigint("id", { mode: "number" }).primaryKey().autoincrement(),
clawId: varchar("claw_id", { length: 21 }).notNull(),
date: varchar("date", { length: 10 }).notNull(), // YYYY-MM-DD
inputTokens: bigint("input_tokens", { mode: "number" }).notNull().default(0),
outputTokens: bigint("output_tokens", { mode: "number" }).notNull().default(0),
createdAt: datetime("created_at").default(sql`NOW()`),
updatedAt: datetime("updated_at").default(sql`NOW()`),
},
(table) => [
index("token_usage_claw_id_idx").on(table.clawId),
index("token_usage_date_idx").on(table.date),
uniqueIndex("token_usage_claw_date_unq").on(table.clawId, table.date),
]
);