feat: 支持批量生图

Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
2026-04-27 01:40:46 +08:00
parent 9a715dede8
commit 7f59b555c6
22 changed files with 1731 additions and 394 deletions
+250 -111
View File
@@ -1,8 +1,9 @@
// server/utils/imageGenerationRecords.ts - 生图相关数据库操作:用户快照、生成记录、历史查询和统计。
// server/utils/imageGenerationRecords.ts - 生图相关数据库操作:用户快照、批次记录、图片子记录、历史查询和统计。
import type { IUserBasicData } from "#shared/types";
import type {
IImageGenerationStatsData,
IImageHistoryDetail,
IImageHistoryImageItem,
IImageHistoryItem,
IImageHistoryListData
} from "#shared/types/openai";
@@ -18,16 +19,16 @@ import { prisma } from "~~/server/utils/prisma";
const GLOBAL_STATS_ID = "global";
const DEFAULT_IMAGE_MODEL = "gpt-image-2";
interface IFinishImageGenerationSuccessInput {
interface IFinishImageGenerationImageSuccessInput {
/** NewAPI 上游返回的生成图片 URL */
imageUrl: string;
/** 上游返回的修订提示词,流式生图通常为空 */
revisedPrompt?: string | null;
/** 完整上游响应,当前为 chat completions 流式聚合对象 */
/** 完整上游响应,仅服务端内部保存 */
upstreamResponse: unknown;
}
interface IFinishImageGenerationArchiveSuccessInput {
interface IFinishImageGenerationImageArchiveSuccessInput {
/** Lsky 图床归档后的图片 URL */
hostedImageUrl: string;
/** 图片 MIME 类型,优先来自图床上传结果 */
@@ -37,14 +38,16 @@ interface IFinishImageGenerationArchiveSuccessInput {
}
export interface IImageArchiveTask {
/** 生图记录 ID */
id: bigint;
/** 生图图片子记录 ID */
imageId: bigint;
/** 所属生图批次记录 ID */
recordId: bigint;
/** NewAPI 用户 ID */
userId: number;
/** 上游生成图片 URL */
imageUrl: string;
/** 记录创建时间,用于构造图床文件名 */
startedAt: Date;
/** 图片子记录创建时间,用于构造图床文件名 */
createdAt: Date;
/** 当前这次归档是第几次尝试 */
archiveAttempts: number;
}
@@ -103,10 +106,11 @@ export const getUserArchiveIdentity = async (userId: number) => {
};
};
/** 创建进行中的生图记录,并递增全局请求进行中统计 */
/** 创建进行中的生图批次和图片子记录,并递增全局请求/进行中统计 */
export const createRunningImageGeneration = async (
userId: number,
prompt: string
prompt: string,
batchSize: number
) => {
await ensureUserRecord(userId);
@@ -115,7 +119,26 @@ export const createRunningImageGeneration = async (
userId,
prompt,
status: ImageGenerationStatus.RUNNING,
model: DEFAULT_IMAGE_MODEL
model: DEFAULT_IMAGE_MODEL,
batchSize,
images: {
create: Array.from({ length: batchSize }, (_, index) => ({
userId,
index,
status: ImageGenerationStatus.RUNNING
}))
}
},
include: {
images: {
orderBy: {
index: "asc"
},
select: {
id: true,
index: true
}
}
}
});
@@ -131,22 +154,17 @@ export const createRunningImageGeneration = async (
return record;
};
/** 将生图记录标记为成功,并先写入上游结果;图床字段稍后由后台归档补写 */
export const finishImageGenerationSuccess = async (
recordId: bigint,
startedAt: Date,
input: IFinishImageGenerationSuccessInput
/** 将单张图片子记录标记为成功,并先写入上游结果;图床字段稍后由后台归档补写 */
export const finishImageGenerationImageSuccess = async (
imageId: bigint,
input: IFinishImageGenerationImageSuccessInput
) => {
const endedAt = new Date();
await prisma.imageGeneration.update({
await prisma.imageGenerationImage.update({
where: {
id: recordId
id: imageId
},
data: {
status: ImageGenerationStatus.SUCCEEDED,
endedAt,
durationMs: getDurationMs(startedAt, endedAt),
imageUrl: input.imageUrl,
hostedImageUrl: null,
imageMimeType: null,
@@ -162,48 +180,115 @@ export const finishImageGenerationSuccess = async (
archiveLastError: null
}
});
};
await safeUpsertGenerationStats({
successRequests: {
increment: 1
/** 将单张图片子记录标记为失败,只保留服务端可排查摘要 */
export const finishImageGenerationImageFailed = async (
imageId: bigint,
error: unknown
) => {
await prisma.imageGenerationImage.update({
where: {
id: imageId
},
runningRequests: {
decrement: 1
},
totalImages: {
increment: 1
data: {
status: ImageGenerationStatus.FAILED,
errorMessage: getSafeErrorMessage(error),
archiveStatus: ImageArchiveStatus.NOT_REQUIRED
}
});
};
/** 将生图记录标记为失败,并保存失败原因和耗时 */
export const finishImageGenerationFailed = async (
recordId: bigint,
startedAt: Date,
error: unknown
) => {
/** 批次内所有图片都结束后,汇总批次状态与全局统计 */
export const finishImageGenerationBatch = async ({
recordId,
startedAt,
successCount,
failedCount,
error
}: {
recordId: bigint;
startedAt: Date;
successCount: number;
failedCount: number;
error?: unknown;
}) => {
const endedAt = new Date();
const hasSuccess = successCount > 0;
await prisma.imageGeneration.update({
where: {
id: recordId
},
data: {
status: ImageGenerationStatus.FAILED,
status: hasSuccess
? ImageGenerationStatus.SUCCEEDED
: ImageGenerationStatus.FAILED,
endedAt,
durationMs: getDurationMs(startedAt, endedAt),
errorMessage: getSafeErrorMessage(error)
successCount,
failedCount,
errorMessage: hasSuccess ? null : getSafeErrorMessage(error)
}
});
await safeUpsertGenerationStats({
failedRequests: {
increment: 1
},
successRequests: hasSuccess
? {
increment: 1
}
: undefined,
failedRequests: hasSuccess
? undefined
: {
increment: 1
},
runningRequests: {
decrement: 1
},
totalImages:
successCount > 0
? {
increment: successCount
}
: undefined
});
};
/** 兼容旧调用:主链路异常且尚未逐图结算时,把整个批次标记为失败 */
export const finishImageGenerationFailed = async (
recordId: bigint,
startedAt: Date,
error: unknown
) => {
const record = await prisma.imageGeneration.findUnique({
where: {
id: recordId
},
select: {
batchSize: true
}
});
await prisma.imageGenerationImage.updateMany({
where: {
imageGenerationId: recordId,
status: ImageGenerationStatus.RUNNING
},
data: {
status: ImageGenerationStatus.FAILED,
errorMessage: getSafeErrorMessage(error),
archiveStatus: ImageArchiveStatus.NOT_REQUIRED
}
});
await finishImageGenerationBatch({
recordId,
startedAt,
successCount: 0,
failedCount: record?.batchSize ?? 1,
error
});
};
/** 领取可执行的图床归档任务;通过 updateMany 条件锁避免多实例重复处理 */
@@ -221,7 +306,7 @@ export const claimRunnableImageArchiveTasks = async ({
const now = new Date();
const staleBefore = new Date(now.getTime() - lockTtlMs);
const runnableWhere = buildRunnableArchiveWhere(now, staleBefore);
const candidates = await prisma.imageGeneration.findMany({
const candidates = await prisma.imageGenerationImage.findMany({
where: runnableWhere,
select: {
id: true
@@ -241,7 +326,7 @@ export const claimRunnableImageArchiveTasks = async ({
for (const candidate of candidates) {
if (tasks.length >= limit) break;
const claimed = await prisma.imageGeneration.updateMany({
const claimed = await prisma.imageGenerationImage.updateMany({
where: {
id: candidate.id,
...runnableWhere
@@ -259,25 +344,27 @@ export const claimRunnableImageArchiveTasks = async ({
if (claimed.count !== 1) continue;
const task = await prisma.imageGeneration.findUnique({
const task = await prisma.imageGenerationImage.findUnique({
where: {
id: candidate.id
},
select: {
id: true,
imageGenerationId: true,
userId: true,
imageUrl: true,
startedAt: true,
createdAt: true,
archiveAttempts: true
}
});
if (task?.imageUrl) {
tasks.push({
id: task.id,
imageId: task.id,
recordId: task.imageGenerationId,
userId: task.userId,
imageUrl: task.imageUrl,
startedAt: task.startedAt,
createdAt: task.createdAt,
archiveAttempts: task.archiveAttempts
});
}
@@ -288,12 +375,12 @@ export const claimRunnableImageArchiveTasks = async ({
/** 后台归档成功后回写图床地址、MIME 和图床响应 */
export const finishImageGenerationArchiveSuccess = async (
recordId: bigint,
input: IFinishImageGenerationArchiveSuccessInput
imageId: bigint,
input: IFinishImageGenerationImageArchiveSuccessInput
) => {
await prisma.imageGeneration.update({
await prisma.imageGenerationImage.update({
where: {
id: recordId
id: imageId
},
data: {
hostedImageUrl: input.hostedImageUrl,
@@ -311,17 +398,17 @@ export const finishImageGenerationArchiveSuccess = async (
/** 归档可重试失败时释放任务锁并安排下一次执行,前端仍显示归档中 */
export const scheduleImageGenerationArchiveRetry = async ({
recordId,
imageId,
nextRunAt,
errorMessage
}: {
recordId: bigint;
imageId: bigint;
nextRunAt: Date;
errorMessage: string;
}) => {
await prisma.imageGeneration.update({
await prisma.imageGenerationImage.update({
where: {
id: recordId
id: imageId
},
data: {
archiveStatus: ImageArchiveStatus.PENDING,
@@ -336,12 +423,12 @@ export const scheduleImageGenerationArchiveRetry = async ({
/** 后台归档最终失败时仅补写本地错误文案,不影响已成功的生图状态 */
export const finishImageGenerationArchiveFailed = async (
recordId: bigint,
imageId: bigint,
errorMessage: string = "图片归档失败"
) => {
await prisma.imageGeneration.update({
await prisma.imageGenerationImage.update({
where: {
id: recordId
id: imageId
},
data: {
archiveStatus: ImageArchiveStatus.FAILED,
@@ -354,7 +441,7 @@ export const finishImageGenerationArchiveFailed = async (
});
};
/** 查询当前用户未删除的生图历史列表,不返回完整上游/图床响应 */
/** 查询当前用户未删除的生图批次历史列表,不返回完整上游/图床响应 */
export const listImageGenerationHistory = async ({
userId,
page,
@@ -373,13 +460,7 @@ export const listImageGenerationHistory = async ({
prisma.imageGeneration.count({ where }),
prisma.imageGeneration.findMany({
where,
include: {
plazaPost: {
select: {
status: true
}
}
},
include: historyInclude,
orderBy: {
createdAt: "desc"
},
@@ -396,7 +477,7 @@ export const listImageGenerationHistory = async ({
};
};
/** 查询当前用户单条生图历史详情,内部响应字段固定隐藏为 null */
/** 查询当前用户单条生图批次详情,内部响应字段固定隐藏为 null */
export const getImageGenerationDetail = async (
userId: number,
recordId: bigint
@@ -407,26 +488,15 @@ export const getImageGenerationDetail = async (
userId,
deletedAt: null
},
include: {
plazaPost: {
select: {
status: true
}
}
}
include: historyInclude
});
if (!record) return null;
return {
...mapImageGenerationItem(record),
imageMimeType: record.imageMimeType,
upstreamResponse: null,
hostedResponse: null
};
return mapImageGenerationItem(record);
};
/** 软删除当前用户单条生图历史 */
/** 软删除当前用户单条生图批次历史 */
export const softDeleteImageGeneration = async (
userId: number,
recordId: bigint
@@ -482,8 +552,12 @@ const upsertGenerationStats = (update: Prisma.GenerationStatsUpdateInput) => {
const safeUpsertGenerationStats = async (
update: Prisma.GenerationStatsUpdateInput
) => {
const cleanUpdate = Object.fromEntries(
Object.entries(update).filter(([, value]) => value !== undefined)
) as Prisma.GenerationStatsUpdateInput;
try {
await upsertGenerationStats(update);
await upsertGenerationStats(cleanUpdate);
} catch (error) {
consola.error("[imageGenerationRecords] 更新生图统计失败", {
message: error instanceof Error ? error.message : String(error)
@@ -503,14 +577,16 @@ const buildStatsCreateInput = (update: Prisma.GenerationStatsUpdateInput) => {
};
};
/** 只领取成功生成、未删除、已到执行时间或锁超时的归档任务 */
/** 只领取成功生成、所属批次未删除、已到执行时间或锁超时的归档任务 */
const buildRunnableArchiveWhere = (now: Date, staleBefore: Date) => {
return {
status: ImageGenerationStatus.SUCCEEDED,
deletedAt: null,
imageUrl: {
not: null
},
imageGeneration: {
deletedAt: null
},
OR: [
{
archiveStatus: ImageArchiveStatus.PENDING,
@@ -532,7 +608,7 @@ const buildRunnableArchiveWhere = (now: Date, staleBefore: Date) => {
}
}
]
} satisfies Prisma.ImageGenerationWhereInput;
} satisfies Prisma.ImageGenerationImageWhereInput;
};
/** 从 Prisma increment 操作里取出增量;非 increment 操作在创建时按 0 处理 */
@@ -549,43 +625,97 @@ const getIncrementValue = (value: unknown): number => {
return 0;
};
/** 将 Prisma 记录转换为前端类型,BigInt/Date 在这里统一序列化 */
const mapImageGenerationItem = (record: {
id: bigint;
userId: number;
prompt: string;
status: ImageGenerationStatus;
model: string;
startedAt: Date;
endedAt: Date | null;
durationMs: number | null;
imageUrl: string | null;
hostedImageUrl: string | null;
revisedPrompt: string | null;
errorMessage: string | null;
createdAt: Date;
plazaPost?: {
status: PlazaPostStatus;
} | null;
}): IImageHistoryItem => {
const historyInclude = {
images: {
orderBy: {
index: "asc" as const
}
},
plazaPost: {
select: {
status: true,
coverImageId: true,
images: {
select: {
imageGenerationImageId: true
}
}
}
}
};
type ImageGenerationWithHistory = Prisma.ImageGenerationGetPayload<{
include: typeof historyInclude;
}>;
/** 将 Prisma 批次记录转换为前端类型,BigInt/Date 在这里统一序列化 */
const mapImageGenerationItem = (
record: ImageGenerationWithHistory
): IImageHistoryItem => {
const images = record.images.map((image) =>
mapImageGenerationImageItem(image, record.plazaPost)
);
const publicImageIds = getPublicImageIds(record.plazaPost);
return {
id: record.id.toString(),
userId: record.userId,
prompt: record.prompt,
status: record.status,
model: record.model,
batchSize: record.batchSize,
successCount: record.successCount,
failedCount: record.failedCount,
startedAt: record.startedAt.toISOString(),
endedAt: record.endedAt?.toISOString() ?? null,
durationMs: record.durationMs,
imageUrl: record.imageUrl,
hostedImageUrl: record.hostedImageUrl,
revisedPrompt: record.revisedPrompt,
errorMessage: getPublicRecordMessage(record.status, record.errorMessage),
isPublic: record.plazaPost?.status === PlazaPostStatus.PUBLIC,
errorMessage: getPublicBatchMessage(record.status, record.errorMessage),
isPublic:
record.plazaPost?.status === PlazaPostStatus.PUBLIC &&
publicImageIds.size > 0,
coverImageId: record.plazaPost?.coverImageId?.toString() ?? null,
images,
createdAt: record.createdAt.toISOString()
};
};
const mapImageGenerationImageItem = (
image: ImageGenerationWithHistory["images"][number],
plazaPost: ImageGenerationWithHistory["plazaPost"]
): IImageHistoryImageItem => {
const publicImageIds = getPublicImageIds(plazaPost);
return {
id: image.id.toString(),
index: image.index,
status: image.status,
imageUrl: image.imageUrl,
hostedImageUrl: image.hostedImageUrl,
imageMimeType: image.imageMimeType,
revisedPrompt: image.revisedPrompt,
errorMessage: getPublicImageMessage(image.status, image.errorMessage),
isPublic:
plazaPost?.status === PlazaPostStatus.PUBLIC && publicImageIds.has(image.id),
isCover:
plazaPost?.status === PlazaPostStatus.PUBLIC &&
plazaPost.coverImageId === image.id,
createdAt: image.createdAt.toISOString()
};
};
/** 展示图优先使用公开封面,其次使用第一张成功图,再兜底第一张子记录 */
const getPublicImageIds = (
plazaPost: ImageGenerationWithHistory["plazaPost"]
): Set<bigint> => {
if (!plazaPost || plazaPost.status !== PlazaPostStatus.PUBLIC) {
return new Set();
}
return new Set(
plazaPost.images.map((image) => image.imageGenerationImageId)
);
};
/** 计算耗时并兜底为非负数,避免系统时间抖动导致负值 */
const getDurationMs = (startedAt: Date, endedAt: Date) => {
return Math.max(0, endedAt.getTime() - startedAt.getTime());
@@ -598,8 +728,17 @@ const getSafeErrorMessage = (error: unknown): string => {
return "图片生成失败";
};
/** 返回给前端的记录错误只保留本地泛化文案,具体内部错误留在数据库和服务端日志 */
const getPublicRecordMessage = (
/** 批次错误返回本地泛化文案,具体内部错误留在数据库和服务端日志 */
const getPublicBatchMessage = (
status: ImageGenerationStatus,
errorMessage: string | null
): string | null => {
if (!errorMessage) return null;
return status === ImageGenerationStatus.FAILED ? "图片生成失败" : null;
};
/** 图片错误返回本地泛化文案,归档失败和生成失败分开表达 */
const getPublicImageMessage = (
status: ImageGenerationStatus,
errorMessage: string | null
): string | null => {