feat: 后端 SQLite→PostgreSQL 迁移(双驱动)——codes/showcase/sync/chibi/payment/security 全链路支持 pg,修复 grant 保留字,schema 双 DDL 导出
This commit is contained in:
1 parent
346f41d391
commit
605af4cdd3
17 files changed
+1516
-2202
No files matched your search
@@ -5,7 +5,7 @@
|
||||
* 组装提示词 -> 调用 OpenAI 兼容图像接口 (AI_IMAGE_API_URL /
|
||||
* AI_IMAGE_API_KEY),未配置接口地址时使用内置 mock 模式生成占位图。
|
||||
*/
|
||||
import type Database from "better-sqlite3";
|
||||
import type { Db } from "../db/index.js";
|
||||
import { deflateSync } from "node:zlib";
|
||||
import type { AccessInfo } from "../types/index.js";
|
||||
import { consumeCode, CodeError, createDownloadGrant } from "../codes/service.js";
|
||||
@@ -52,7 +52,7 @@ export class ChibiError extends Error {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mock 占位图 (纯函数实现的最小合法 PNG: 纯色 RGB + gridSize 尺寸)
|
||||
// Mock 占位图
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
@@ -89,14 +89,13 @@ function pngChunk(type: string, data: Buffer): Buffer {
|
||||
/** 生成 size×size 纯色 PNG,返回 base64 dataURL。 */
|
||||
function makePlaceholderPng(size: number, rgb: readonly [number, number, number]): string {
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(size, 0); // width
|
||||
ihdr.writeUInt32BE(size, 4); // height
|
||||
ihdr.writeUInt8(8, 8); // bit depth
|
||||
ihdr.writeUInt8(2, 9); // color type: truecolor RGB
|
||||
// bytes 10/11/12: compression / filter / interlace,默认 0
|
||||
ihdr.writeUInt32BE(size, 0);
|
||||
ihdr.writeUInt32BE(size, 4);
|
||||
ihdr.writeUInt8(8, 8);
|
||||
ihdr.writeUInt8(2, 9);
|
||||
|
||||
const row = Buffer.alloc(1 + size * 3);
|
||||
row.writeUInt8(0, 0); // filter: none
|
||||
row.writeUInt8(0, 0);
|
||||
for (let x = 0; x < size; x++) {
|
||||
row.writeUInt8(rgb[0], 1 + x * 3);
|
||||
row.writeUInt8(rgb[1], 2 + x * 3);
|
||||
@@ -112,25 +111,18 @@ function makePlaceholderPng(size: number, rgb: readonly [number, number, number]
|
||||
return `data:image/png;base64,${png.toString("base64")}`;
|
||||
}
|
||||
|
||||
/** 每类一个主题色,mock 模式下占位图随分类变色,便于肉眼区分。 */
|
||||
const CATEGORY_COLORS: Record<ChibiCategory, readonly [number, number, number]> = {
|
||||
landscape: [96, 165, 250], // 天空蓝
|
||||
person: [251, 146, 60], // 活力橙
|
||||
pet: [167, 139, 250], // 香芋紫
|
||||
object: [52, 211, 153], // 抹茶绿
|
||||
food: [251, 113, 133], // 蜜桃粉
|
||||
landscape: [96, 165, 250],
|
||||
person: [251, 146, 60],
|
||||
pet: [167, 139, 250],
|
||||
object: [52, 211, 153],
|
||||
food: [251, 113, 133],
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// AI 接口调用 (OpenAI 兼容)
|
||||
// AI 接口调用
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 从 OpenAI 兼容响应中提取 base64 (或图像 url)。
|
||||
* 支持两种形态:
|
||||
* /v1/images/generations -> { data: [{ b64_json | url }] }
|
||||
* /v1/chat/completions -> { choices: [{ message: { images: [{ b64_json | url }] } }] }
|
||||
*/
|
||||
function extractImageBase64(payload: unknown): string | null {
|
||||
if (!payload || typeof payload !== "object") return null;
|
||||
const root = payload as Record<string, unknown>;
|
||||
@@ -161,7 +153,6 @@ async function requestAiImage(prompt: string, req: GenerateRequest): Promise<str
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
|
||||
|
||||
// chat/completions 走多模态消息 (携带原图/参考图),images/generations 走纯提示词
|
||||
const isChat = (apiUrl ?? "").includes("/chat/completions");
|
||||
let payload: unknown;
|
||||
if (isChat) {
|
||||
@@ -205,7 +196,6 @@ async function requestAiImage(prompt: string, req: GenerateRequest): Promise<str
|
||||
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
|
||||
}
|
||||
if (b64OrUrl.startsWith("http://") || b64OrUrl.startsWith("https://")) {
|
||||
// 接口返回 url 时下载并转为 base64 dataURL
|
||||
let imgRes: Awaited<ReturnType<typeof fetch>>;
|
||||
try {
|
||||
imgRes = await fetch(b64OrUrl, { signal: AbortSignal.timeout(60_000) });
|
||||
@@ -223,10 +213,6 @@ async function requestAiImage(prompt: string, req: GenerateRequest): Promise<str
|
||||
return b64OrUrl.startsWith("data:") ? b64OrUrl : `data:image/png;base64,${b64OrUrl}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成图像。未配置 AI_IMAGE_API_URL 时进入 mock 模式,返回 gridSize
|
||||
* 尺寸的纯色占位 PNG (dataURL)。
|
||||
*/
|
||||
async function generateImage(prompt: string, req: GenerateRequest): Promise<string> {
|
||||
const apiUrl = process.env["AI_IMAGE_API_URL"];
|
||||
if (!apiUrl) {
|
||||
@@ -240,11 +226,10 @@ async function generateImage(prompt: string, req: GenerateRequest): Promise<stri
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 生成 chibi 拼豆图。先原子消耗一次兑换码次数(无剩余次数时抛出
|
||||
* ChibiError "生成次数不足", 402),再调用 AI 接口。
|
||||
* 生成 chibi 拼豆图。先原子消耗一次兑换码次数,再调用 AI 接口。
|
||||
*/
|
||||
export async function generateChibiImage(
|
||||
db: Database.Database,
|
||||
db: Db,
|
||||
req: GenerateRequest,
|
||||
): Promise<GenerateOutcome> {
|
||||
// 1. 组装提示词
|
||||
@@ -259,13 +244,12 @@ export async function generateChibiImage(
|
||||
hasReferenceImage: req.referenceImage !== undefined && req.referenceImage !== "",
|
||||
});
|
||||
|
||||
// 2. 消耗一次次数 (原子校验 + 扣减)
|
||||
// 2. 消耗一次次数
|
||||
let access: AccessInfo;
|
||||
try {
|
||||
access = consumeCode(db, req.code);
|
||||
access = await consumeCode(db, req.code);
|
||||
} catch (err) {
|
||||
if (err instanceof CodeError) {
|
||||
// 未找到 / 禁用 / 过期 / 用尽 统一视为无法生成
|
||||
throw new ChibiError("生成次数不足", 402);
|
||||
}
|
||||
throw err;
|
||||
@@ -274,8 +258,8 @@ export async function generateChibiImage(
|
||||
// 3. 生成图片
|
||||
const image = await generateImage(prompt, req);
|
||||
|
||||
// 4. 写入一次性下载授权凭证(下载时必须携带,防止绕过生成直接消耗次数)
|
||||
const downloadGrant = createDownloadGrant(db, req.code);
|
||||
// 4. 写入一次性下载授权凭证
|
||||
const downloadGrant = await createDownloadGrant(db, req.code);
|
||||
|
||||
return { image, downloadGrant, access };
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
import type Database from "better-sqlite3";
|
||||
import type { Db } from "../db/index.js";
|
||||
import { getDb } from "../db/index.js";
|
||||
import { generateChibiImage, ChibiError, type GenerateRequest } from "./generate.js";
|
||||
import { findTemplate, type ChibiCategory, type Composition } from "./prompts.js";
|
||||
@@ -9,8 +9,8 @@ import { createRateLimiter, RATE_LIMITS } from "../security/rate-limit.js";
|
||||
const CATEGORIES: readonly ChibiCategory[] = ["landscape", "person", "pet", "object", "food"];
|
||||
const COMPOSITIONS: readonly Composition[] = ["主体特写", "半幅构图", "完整构图"];
|
||||
|
||||
/** Resolve the database instance: injected DB for tests, else global singleton. */
|
||||
function resolveDb(injected?: Database.Database): Database.Database {
|
||||
/** Resolve the database instance. */
|
||||
function resolveDb(injected?: Db): Db {
|
||||
return injected ?? getDb();
|
||||
}
|
||||
|
||||
@@ -21,22 +21,18 @@ function resolveDb(injected?: Database.Database): Database.Database {
|
||||
* Request: { code, image, referenceImage?, category, subtype, gridSize,
|
||||
* colorCount, composition, detailTags, customPrompt? }
|
||||
* Response: 200 { image, access, downloadGrant }
|
||||
* 400 参数错误 (中文提示)
|
||||
* 402 { error: "生成次数不足" }
|
||||
* 500 服务器内部错误
|
||||
* 502 AI 图像生成失败
|
||||
* 400 / 402 / 500 / 502
|
||||
*/
|
||||
export function createChibiRouter(injectedDb?: Database.Database): Router {
|
||||
export function createChibiRouter(injectedDb?: Db): Router {
|
||||
const router = Router();
|
||||
|
||||
// 防刷限流:AI 生成 10 次/小时/IP(每路由实例独立计数,测试互不干扰)
|
||||
// 防刷限流
|
||||
const chibiLimiter = createRateLimiter(RATE_LIMITS.chibiGenerate)("chibi_generate");
|
||||
|
||||
router.post("/generate", chibiLimiter, async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const body = (req.body ?? {}) as Record<string, unknown>;
|
||||
|
||||
// ---- 基础字段校验 ----
|
||||
const code = typeof body.code === "string" ? body.code : "";
|
||||
if (!code) {
|
||||
res.status(400).json({ error: "请输入兑换码" });
|
||||
@@ -52,7 +48,6 @@ export function createChibiRouter(injectedDb?: Database.Database): Router {
|
||||
? body.referenceImage
|
||||
: undefined;
|
||||
|
||||
// ---- 分类 / 细分模板 ----
|
||||
const category = body.category as ChibiCategory;
|
||||
if (!CATEGORIES.includes(category)) {
|
||||
res.status(400).json({ error: "未知的分类" });
|
||||
@@ -66,7 +61,6 @@ export function createChibiRouter(injectedDb?: Database.Database): Router {
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- 构图 / 网格 / 颜色 ----
|
||||
const composition = body.composition as Composition;
|
||||
if (!COMPOSITIONS.includes(composition)) {
|
||||
res.status(400).json({ error: "未知的构图方式" });
|
||||
@@ -83,7 +77,6 @@ export function createChibiRouter(injectedDb?: Database.Database): Router {
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- 细节标签 / 自定义提示词 ----
|
||||
const detailTags = Array.isArray(body.detailTags)
|
||||
? body.detailTags.filter((t): t is string => typeof t === "string")
|
||||
: [];
|
||||
@@ -122,4 +115,4 @@ export function createChibiRouter(injectedDb?: Database.Database): Router {
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user