Compare commits
9 Commits
codex/lega
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 3f52e24076 | |||
| 0b74e71a33 | |||
| 4f8c1a5d5d | |||
| 33662210dd | |||
| 71413c173e | |||
| dbe96db34d | |||
| dfaeb9f09d | |||
| 46abb8259a | |||
| 3b3b5bc78a |
@ -3,6 +3,7 @@ import { isRetiredStorageUrl, normalizeLegacyAliyunStorageUrl, RETIRED_STORAGE_M
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { formatDownloadFailure, getDownloadFailure } from "@/lib/canvas/download-error";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
import { buildImageProxyUrl, isAlibabaModelImageUrl } from "@/lib/image-delivery";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
const logger = createLogger("image.download");
|
||||
@ -242,6 +243,7 @@ function resolveDirectImageTarget(
|
||||
requestedQuality: number | null,
|
||||
requestedFormat: string | null
|
||||
): URL | null {
|
||||
if (isAlibabaModelImageUrl(target.toString())) return null;
|
||||
if (!isBrowserImageRequest(request)) {
|
||||
return null;
|
||||
}
|
||||
@ -336,6 +338,25 @@ export async function GET(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
if (!original && isAlibabaModelImageUrl(target.toString())) {
|
||||
try {
|
||||
const { getArchivedImageUrlMappings } = await import("@/lib/storage/image-archive-db");
|
||||
const mappings = await getArchivedImageUrlMappings([target.toString()]);
|
||||
const archived = mappings[target.toString()];
|
||||
if (archived) {
|
||||
const preview = buildImageProxyUrl(archived, {
|
||||
width: width || undefined,
|
||||
quality,
|
||||
format: ["webp", "avif", "jpeg", "png"].includes(requestedFormat || "") ? requestedFormat as OutputFormat : undefined,
|
||||
});
|
||||
if (/^https?:\/\//i.test(preview)) return redirectToDirectImage(new URL(preview));
|
||||
target = new URL(archived);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn("preview_archive_lookup_failed", error, { requestId });
|
||||
}
|
||||
}
|
||||
|
||||
if (original && searchParams.get("download") === "resolve") {
|
||||
try {
|
||||
const { buildImageProxyUrl } = await import("@/lib/image-delivery");
|
||||
@ -388,7 +409,7 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const fetchSignal = AbortSignal.any([
|
||||
request.signal,
|
||||
AbortSignal.timeout(original ? 60_000 : width && width <= 256 ? SMALL_PREVIEW_FETCH_TIMEOUT_MS : FETCH_TIMEOUT_MS),
|
||||
AbortSignal.timeout(original ? 60_000 : isAlibabaModelImageUrl(target.toString()) || width && width <= 256 ? SMALL_PREVIEW_FETCH_TIMEOUT_MS : FETCH_TIMEOUT_MS),
|
||||
]);
|
||||
const upstreamFailure = (error: unknown) => {
|
||||
if (request.signal.aborted) return new NextResponse(null, { status: 499 });
|
||||
@ -399,37 +420,51 @@ export async function GET(request: NextRequest) {
|
||||
{ status: timedOut ? 504 : 502 },
|
||||
);
|
||||
};
|
||||
let upstreamResponse: Response;
|
||||
try {
|
||||
upstreamResponse = await fetch(target.toString(), {
|
||||
signal: fetchSignal,
|
||||
headers: {
|
||||
Accept: original ? "*/*" : "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return upstreamFailure(error);
|
||||
}
|
||||
|
||||
if (!upstreamResponse.ok) {
|
||||
if (original) return downloadFailure(`HTTP ${upstreamResponse.status}`);
|
||||
return NextResponse.json(
|
||||
{ error: `Upstream responded with ${upstreamResponse.status}` },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
|
||||
const contentType = upstreamResponse.headers.get("content-type") || "application/octet-stream";
|
||||
if (!contentType.toLowerCase().startsWith("image/")) {
|
||||
if (original) return downloadFailure("Source is not an image");
|
||||
return NextResponse.json({ error: "Upstream is not an image" }, { status: 400 });
|
||||
}
|
||||
|
||||
let contentType: string;
|
||||
let originalBuffer: Buffer;
|
||||
try {
|
||||
originalBuffer = Buffer.from(await upstreamResponse.arrayBuffer());
|
||||
} catch (error) {
|
||||
return upstreamFailure(error);
|
||||
if (!original && isAlibabaModelImageUrl(target.toString())) {
|
||||
try {
|
||||
const { fetchImageBytes } = await import("@/lib/storage/image-byte-cache");
|
||||
const data = await fetchImageBytes(target.toString(), { timeoutMs: SMALL_PREVIEW_FETCH_TIMEOUT_MS });
|
||||
originalBuffer = data.buffer;
|
||||
contentType = data.contentType;
|
||||
if (request.signal.aborted) return new NextResponse(null, { status: 499 });
|
||||
if (!contentType.toLowerCase().startsWith("image/")) {
|
||||
return NextResponse.json({ error: "Upstream is not an image" }, { status: 400 });
|
||||
}
|
||||
} catch (error) {
|
||||
return upstreamFailure(error);
|
||||
}
|
||||
} else {
|
||||
let upstreamResponse: Response;
|
||||
try {
|
||||
upstreamResponse = await fetch(target.toString(), {
|
||||
signal: fetchSignal,
|
||||
headers: {
|
||||
Accept: original ? "*/*" : "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return upstreamFailure(error);
|
||||
}
|
||||
|
||||
if (!upstreamResponse.ok) {
|
||||
if (original) return downloadFailure(`HTTP ${upstreamResponse.status}`);
|
||||
return NextResponse.json(
|
||||
{ error: `Upstream responded with ${upstreamResponse.status}` },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
contentType = upstreamResponse.headers.get("content-type") || "application/octet-stream";
|
||||
if (!contentType.toLowerCase().startsWith("image/")) {
|
||||
if (original) return downloadFailure("Source is not an image");
|
||||
return NextResponse.json({ error: "Upstream is not an image" }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
originalBuffer = Buffer.from(await upstreamResponse.arrayBuffer());
|
||||
} catch (error) {
|
||||
return upstreamFailure(error);
|
||||
}
|
||||
}
|
||||
if (original) {
|
||||
return buildImageResponse(originalBuffer, {
|
||||
|
||||
@ -82,6 +82,7 @@ import {
|
||||
inferOriginalImageUrl,
|
||||
} from "@/lib/image-url";
|
||||
import { buildImageFallbackUrl, buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
import { ProgressiveImagePreview, type LoadedImagePreview } from "@/components/progressive-image-preview";
|
||||
import {
|
||||
isImageGenerationModelDescriptor,
|
||||
isVideoModelDescriptor,
|
||||
@ -3434,6 +3435,7 @@ export function CanvasChatPanel({
|
||||
const [fullscreenPreview, setFullscreenPreview] = useState<{
|
||||
url: string;
|
||||
alt?: string;
|
||||
preview: LoadedImagePreview;
|
||||
} | null>(null);
|
||||
const [downloadProgress, setDownloadProgress] =
|
||||
useState<CanvasImageDownloadProgress | null>(null);
|
||||
@ -3471,16 +3473,6 @@ export function CanvasChatPanel({
|
||||
const [downloadingOriginalUrl, setDownloadingOriginalUrl] = useState("");
|
||||
const [addingClawdImageUrl, setAddingClawdImageUrl] = useState("");
|
||||
const downloadAbortControllerRef = useRef<AbortController | null>(null);
|
||||
const fullscreenPreviewSrc = useMemo(() => {
|
||||
if (!fullscreenPreview?.url) return "";
|
||||
const originalUrl = inferOriginalImageUrl(fullscreenPreview.url);
|
||||
return buildImageProxyUrl(originalUrl || fullscreenPreview.url, {
|
||||
delivery: "proxy",
|
||||
width: 2400,
|
||||
quality: 90,
|
||||
format: "webp",
|
||||
});
|
||||
}, [fullscreenPreview]);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (composerUploadClearTimeoutRef.current) {
|
||||
@ -17036,11 +17028,19 @@ export function CanvasChatPanel({
|
||||
event.currentTarget.src = buildImageFallbackUrl(url);
|
||||
}
|
||||
}}
|
||||
onClick={() => setFullscreenPreview({ url })}
|
||||
onClick={(event) => setFullscreenPreview({ url, preview: {
|
||||
src: event.currentTarget.currentSrc || event.currentTarget.src,
|
||||
width: event.currentTarget.naturalWidth,
|
||||
height: event.currentTarget.naturalHeight,
|
||||
} })}
|
||||
onDoubleClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setFullscreenPreview({ url });
|
||||
setFullscreenPreview({ url, preview: {
|
||||
src: e.currentTarget.currentSrc || e.currentTarget.src,
|
||||
width: e.currentTarget.naturalWidth,
|
||||
height: e.currentTarget.naturalHeight,
|
||||
} });
|
||||
}}
|
||||
/>
|
||||
<div className="absolute bottom-2 right-2 flex items-center gap-1.5">
|
||||
@ -17286,7 +17286,7 @@ export function CanvasChatPanel({
|
||||
onClick={() => setFullscreenPreview(null)}
|
||||
>
|
||||
<button
|
||||
className="absolute top-4 right-4 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
|
||||
className="absolute top-4 right-4 z-10 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
|
||||
onClick={() => setFullscreenPreview(null)}
|
||||
aria-label="关闭预览"
|
||||
>
|
||||
@ -17295,7 +17295,7 @@ export function CanvasChatPanel({
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className="absolute top-4 right-16 inline-flex items-center gap-1 rounded-full bg-white/10 px-3 py-2 text-sm text-white transition-colors hover:bg-white/20 disabled:cursor-not-allowed disabled:opacity-65"
|
||||
className="absolute top-4 right-16 z-10 inline-flex items-center gap-1 rounded-full bg-white/10 px-3 py-2 text-sm text-white transition-colors hover:bg-white/20 disabled:cursor-not-allowed disabled:opacity-65"
|
||||
disabled={isDownloadingOriginalImage}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
@ -17312,13 +17312,11 @@ export function CanvasChatPanel({
|
||||
{isDownloadingOriginalImage ? "下载中" : "下载原图"}
|
||||
</button>
|
||||
|
||||
<img
|
||||
src={fullscreenPreviewSrc}
|
||||
<ProgressiveImagePreview
|
||||
src={inferOriginalImageUrl(fullscreenPreview.url) || fullscreenPreview.url}
|
||||
preview={fullscreenPreview.preview}
|
||||
alt={fullscreenPreview.alt || "图片预览"}
|
||||
className="max-w-[95vw] max-h-[95vh] object-contain"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
|
||||
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 text-white/60 text-sm">
|
||||
|
||||
@ -60,6 +60,7 @@ import { DetailUiDomRenderer } from "@/components/canvas/DetailUiDomRenderer";
|
||||
import { ReferenceImageToolbar } from "@/components/canvas/ReferenceImageToolbar";
|
||||
import { CanvasToolbarIcon } from "@/components/canvas/CanvasToolbarIcon";
|
||||
import { CanvasImageDownloadProgressDialog } from "@/components/canvas/CanvasImageDownloadProgressDialog";
|
||||
import { ProgressiveImagePreview, type LoadedImagePreview } from "@/components/progressive-image-preview";
|
||||
import {
|
||||
areImageAdjustmentsEqual,
|
||||
buildImageAdjustmentFilterStyle,
|
||||
@ -1711,6 +1712,7 @@ export function ImageNode({
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [annotatorOpen, setAnnotatorOpen] = useState(false);
|
||||
const [fullscreenPreviewOpen, setFullscreenPreviewOpen] = useState(false);
|
||||
const [fullscreenPreviewImage, setFullscreenPreviewImage] = useState<LoadedImagePreview | null>(null);
|
||||
const [downloadProgress, setDownloadProgress] =
|
||||
useState<CanvasImageDownloadProgress | null>(null);
|
||||
const downloadAbortControllerRef = useRef<AbortController | null>(null);
|
||||
@ -8559,6 +8561,11 @@ export function ImageNode({
|
||||
onDoubleClick={(e) => {
|
||||
if (!isThisNodePicking && !boxCutoutMode && !localEditMode) {
|
||||
e.stopPropagation();
|
||||
setFullscreenPreviewImage({
|
||||
src: e.currentTarget.currentSrc || e.currentTarget.src,
|
||||
width: e.currentTarget.naturalWidth,
|
||||
height: e.currentTarget.naturalHeight,
|
||||
});
|
||||
setFullscreenPreviewOpen(true);
|
||||
}
|
||||
}}
|
||||
@ -11964,6 +11971,7 @@ export function ImageNode({
|
||||
{/* 双击放大预览弹窗 */}
|
||||
{fullscreenPreviewOpen &&
|
||||
data.src &&
|
||||
fullscreenPreviewImage &&
|
||||
createPortal(
|
||||
<div
|
||||
className="fixed inset-0 z-[9999] flex cursor-zoom-out items-center justify-center bg-black/90"
|
||||
@ -11971,7 +11979,7 @@ export function ImageNode({
|
||||
>
|
||||
{/* 关闭按钮 */}
|
||||
<button
|
||||
className="absolute top-4 right-4 rounded-full bg-slate-950 p-2 transition-colors hover:bg-black"
|
||||
className="absolute top-4 right-4 z-10 rounded-full bg-slate-950 p-2 transition-colors hover:bg-black"
|
||||
onClick={() => setFullscreenPreviewOpen(false)}
|
||||
>
|
||||
<svg
|
||||
@ -11989,7 +11997,7 @@ export function ImageNode({
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className="absolute top-4 right-16 inline-flex items-center gap-1.5 rounded-full bg-slate-950 px-3 py-2 text-sm text-white transition-colors hover:bg-black disabled:cursor-not-allowed disabled:opacity-60"
|
||||
className="absolute top-4 right-16 z-10 inline-flex items-center gap-1.5 rounded-full bg-slate-950 px-3 py-2 text-sm text-white transition-colors hover:bg-black disabled:cursor-not-allowed disabled:opacity-60"
|
||||
disabled={isDownloadingOriginalImage}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
@ -12008,13 +12016,11 @@ export function ImageNode({
|
||||
</button>
|
||||
|
||||
{/* 图片 */}
|
||||
<img
|
||||
<ProgressiveImagePreview
|
||||
alt={data.prompt || "图片预览"}
|
||||
className="max-h-[95vh] max-w-[95vw] object-contain"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
src={fullscreenPreviewSrc}
|
||||
src={resolveOriginalImageUrl(data.src) || data.src}
|
||||
preview={fullscreenPreviewImage}
|
||||
style={activeImageAdjustmentsStyle}
|
||||
/>
|
||||
|
||||
|
||||
74
components/progressive-image-preview.tsx
Normal file
74
components/progressive-image-preview.tsx
Normal file
@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type CSSProperties, type MouseEventHandler } from "react";
|
||||
import { buildImageProxyUrl, getFullscreenPreviewSize } from "@/lib/image-delivery";
|
||||
|
||||
export type LoadedImagePreview = { src: string; width: number; height: number };
|
||||
|
||||
/** Keep the already displayed image visible while its larger preview loads. */
|
||||
export function ProgressiveImagePreview({
|
||||
src,
|
||||
preview,
|
||||
alt,
|
||||
className,
|
||||
style,
|
||||
onClick,
|
||||
}: {
|
||||
src: string;
|
||||
preview: LoadedImagePreview;
|
||||
alt: string;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
onClick?: MouseEventHandler<HTMLImageElement>;
|
||||
}) {
|
||||
const size = getFullscreenPreviewSize({
|
||||
imageWidth: preview.width,
|
||||
imageHeight: preview.height,
|
||||
viewportWidth: typeof window === "undefined" ? 1280 : window.innerWidth,
|
||||
viewportHeight: typeof window === "undefined" ? 900 : window.innerHeight,
|
||||
pixelRatio: typeof window === "undefined" ? 1 : window.devicePixelRatio,
|
||||
});
|
||||
const fullSrc = buildImageProxyUrl(src, {
|
||||
delivery: "proxy",
|
||||
width: size.requestWidth,
|
||||
quality: 86,
|
||||
format: "webp",
|
||||
});
|
||||
const [loadedSrc, setLoadedSrc] = useState("");
|
||||
const [failedSrc, setFailedSrc] = useState("");
|
||||
const ready = fullSrc === preview.src || loadedSrc === fullSrc;
|
||||
const failed = failedSrc === fullSrc;
|
||||
|
||||
useEffect(() => {
|
||||
if (fullSrc === preview.src) return;
|
||||
const image = new Image();
|
||||
image.decoding = "async";
|
||||
image.onload = () => setLoadedSrc(fullSrc);
|
||||
image.onerror = () => setFailedSrc(fullSrc);
|
||||
image.src = fullSrc;
|
||||
return () => {
|
||||
image.onload = null;
|
||||
image.onerror = null;
|
||||
image.removeAttribute("src");
|
||||
};
|
||||
}, [fullSrc, preview.src]);
|
||||
|
||||
return (
|
||||
<div className="relative flex items-center justify-center" onClick={(event) => event.stopPropagation()}>
|
||||
<img
|
||||
alt={alt}
|
||||
className={className}
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
onClick={onClick}
|
||||
src={ready ? fullSrc : preview.src}
|
||||
style={{ width: size.displayWidth, ...style }}
|
||||
/>
|
||||
{!ready && (
|
||||
<div role="status" className="pointer-events-none absolute bottom-4 max-w-full rounded-lg bg-black/80 px-3 py-2 text-center text-sm text-white">
|
||||
{failed ? "高清预览加载失败,已保留当前预览;可关闭后重试或下载原图" : "正在加载高清预览…"}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -27,6 +27,7 @@ type RmbgConfig = {
|
||||
};
|
||||
|
||||
export type ExecuteRmbgJobParams = {
|
||||
requestId?: string;
|
||||
userId: string;
|
||||
imageBuffer: Buffer;
|
||||
imageBase64?: string;
|
||||
@ -53,7 +54,7 @@ export class RmbgServiceError extends Error {
|
||||
detail?: string;
|
||||
|
||||
constructor(message: string, status = 500, detail?: string) {
|
||||
super(message);
|
||||
super(detail && detail !== message ? `${message}:${detail}` : message);
|
||||
this.name = "RmbgServiceError";
|
||||
this.status = status;
|
||||
this.detail = detail;
|
||||
@ -147,6 +148,18 @@ const withTimeout = async <T,>(
|
||||
}
|
||||
};
|
||||
|
||||
async function readAosResult<T>(read: (signal: AbortSignal) => Promise<T>, timeoutMs: number): Promise<T> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
return await withTimeout(read, timeoutMs);
|
||||
} catch (error) {
|
||||
const name = error instanceof Error ? error.name : "";
|
||||
if (attempt >= 2 || (name !== "TypeError" && name !== "AbortError")) throw error;
|
||||
await sleep(1000 * (attempt + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getAosFriendlyErrorMessage(detail: string): string | null {
|
||||
const resolutionMatch = detail.match(/resolution excess,\s*width=(\d+),\s*height=(\d+)/i);
|
||||
if (resolutionMatch) {
|
||||
@ -163,7 +176,7 @@ function getAosFriendlyErrorMessage(detail: string): string | null {
|
||||
|
||||
async function prepareImageForAos(
|
||||
imageBuffer: Buffer
|
||||
): Promise<{ buffer: Buffer; mimeType: string; filename: string }> {
|
||||
): Promise<{ buffer: Buffer; mimeType: string; filename: string; resized: boolean }> {
|
||||
try {
|
||||
const sharp = await import("sharp");
|
||||
const image = sharp.default(imageBuffer);
|
||||
@ -189,6 +202,7 @@ async function prepareImageForAos(
|
||||
buffer: imageBuffer,
|
||||
mimeType,
|
||||
filename: `image.${filenameExt}`,
|
||||
resized: false,
|
||||
};
|
||||
}
|
||||
|
||||
@ -203,10 +217,11 @@ async function prepareImageForAos(
|
||||
buffer: resizedBuffer,
|
||||
mimeType,
|
||||
filename: `image.${filenameExt}`,
|
||||
resized: true,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.warn("aos_image_preprocess_failed", error);
|
||||
return { buffer: imageBuffer, mimeType: "image/png", filename: "image.png" };
|
||||
return { buffer: imageBuffer, mimeType: "image/png", filename: "image.png", resized: true };
|
||||
}
|
||||
}
|
||||
|
||||
@ -369,20 +384,38 @@ async function processWithAosSegmentation(
|
||||
foregroundType?: "" | "person" | "object" | "stamp";
|
||||
crop?: 0 | 1;
|
||||
format?: "png" | "jpg";
|
||||
sourceImageUrl?: string | null;
|
||||
requestId?: string;
|
||||
}
|
||||
): Promise<{ success: boolean; imageBuffer?: Buffer; processing_time?: number; error?: string }> {
|
||||
const startTime = Date.now();
|
||||
const baseUrl = (config.apiBaseUrl || "https://techsz.aoscdn.com").replace(/\/+$/, "");
|
||||
const createUrl = `${baseUrl}/api/tasks/visual/segmentation`;
|
||||
const headers = { "X-API-KEY": config.apiKey };
|
||||
let stage = "create";
|
||||
let providerTaskId: string | undefined;
|
||||
|
||||
try {
|
||||
const normalizedImage = await prepareImageForAos(imageBuffer);
|
||||
const createForm = new FormData();
|
||||
const imageBlob = new Blob([new Uint8Array(normalizedImage.buffer)], {
|
||||
type: normalizedImage.mimeType,
|
||||
});
|
||||
createForm.append("image_file", imageBlob, normalizedImage.filename);
|
||||
let publicSourceUrl: string | null = null;
|
||||
if (!normalizedImage.resized && config.sourceImageUrl) {
|
||||
try {
|
||||
const source = new URL(config.sourceImageUrl);
|
||||
const cdn = new URL(process.env.NEXT_PUBLIC_CANVAS_CDN_ORIGIN || "");
|
||||
if (["http:", "https:"].includes(source.protocol) && source.hostname === cdn.hostname) {
|
||||
publicSourceUrl = source.toString();
|
||||
}
|
||||
} catch { /* Uploaded files and other sources use the file API. */ }
|
||||
}
|
||||
if (publicSourceUrl) {
|
||||
createForm.append("image_url", publicSourceUrl);
|
||||
} else {
|
||||
const imageBlob = new Blob([new Uint8Array(normalizedImage.buffer)], {
|
||||
type: normalizedImage.mimeType,
|
||||
});
|
||||
createForm.append("image_file", imageBlob, normalizedImage.filename);
|
||||
}
|
||||
createForm.append("sync", "0");
|
||||
createForm.append("return_type", "1");
|
||||
createForm.append("output_type", "2");
|
||||
@ -392,6 +425,9 @@ async function processWithAosSegmentation(
|
||||
createForm.append("type", config.foregroundType);
|
||||
}
|
||||
|
||||
const createStartedAt = Date.now();
|
||||
logger.info("aos_task_create_started", { requestId: config.requestId, sourceMode: publicSourceUrl ? "url" : "file", inputBytes: imageBuffer.length, uploadBytes: publicSourceUrl ? 0 : normalizedImage.buffer.length });
|
||||
|
||||
const createResponse = await withTimeout(
|
||||
(signal) =>
|
||||
fetch(createUrl, {
|
||||
@ -416,23 +452,32 @@ async function processWithAosSegmentation(
|
||||
}
|
||||
|
||||
const taskId = createPayload.data.task_id as string;
|
||||
providerTaskId = taskId;
|
||||
logger.info("aos_task_created", { requestId: config.requestId, taskId, createMs: Date.now() - createStartedAt });
|
||||
const taskUrl = `${createUrl}/${taskId}`;
|
||||
const maxPollCount = 60;
|
||||
|
||||
for (let pollCount = 0; pollCount < maxPollCount; pollCount += 1) {
|
||||
await sleep(1000);
|
||||
stage = "poll";
|
||||
|
||||
const pollResponse = await withTimeout(
|
||||
(signal) =>
|
||||
fetch(taskUrl, {
|
||||
const pollResponse = await readAosResult(
|
||||
async (signal) => {
|
||||
const response = await fetch(taskUrl, {
|
||||
method: "GET",
|
||||
headers,
|
||||
signal,
|
||||
}),
|
||||
});
|
||||
const payload = await response.json().catch((error) => {
|
||||
if (error instanceof Error && error.name !== "SyntaxError") throw error;
|
||||
return null;
|
||||
});
|
||||
return { ok: response.ok, status: response.status, statusText: response.statusText, payload };
|
||||
},
|
||||
AOS_POLL_TIMEOUT_MS
|
||||
);
|
||||
|
||||
const pollPayload = await pollResponse.json().catch(() => null);
|
||||
const pollPayload = pollResponse.payload;
|
||||
if (!pollResponse.ok || !pollPayload?.data) {
|
||||
logger.warn("aos_task_poll_failed", {
|
||||
hasPayload: pollPayload != null,
|
||||
@ -454,12 +499,15 @@ async function processWithAosSegmentation(
|
||||
pollCount,
|
||||
taskId,
|
||||
});
|
||||
const imageResponse = await withTimeout(
|
||||
(signal) =>
|
||||
fetch(imageUrl, {
|
||||
stage = "download";
|
||||
const imageResponse = await readAosResult(
|
||||
async (signal) => {
|
||||
const response = await fetch(imageUrl, {
|
||||
method: "GET",
|
||||
signal,
|
||||
}),
|
||||
});
|
||||
return { ok: response.ok, status: response.status, statusText: response.statusText, buffer: response.ok ? Buffer.from(await response.arrayBuffer()) : null };
|
||||
},
|
||||
AOS_DOWNLOAD_TIMEOUT_MS
|
||||
);
|
||||
|
||||
@ -474,7 +522,7 @@ async function processWithAosSegmentation(
|
||||
};
|
||||
}
|
||||
|
||||
const resultBuffer = Buffer.from(await imageResponse.arrayBuffer());
|
||||
const resultBuffer = imageResponse.buffer!;
|
||||
return {
|
||||
success: true,
|
||||
imageBuffer: resultBuffer,
|
||||
@ -499,10 +547,21 @@ async function processWithAosSegmentation(
|
||||
return { success: false, error: "AOS任务超时(最多60秒)" };
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
return { success: false, error: "AOS请求超时,请稍后重试" };
|
||||
logger.warn("aos_request_timeout", { requestId: config.requestId, stage, taskId: providerTaskId, inputBytes: imageBuffer.length });
|
||||
const message = stage === "create"
|
||||
? "AOS创建任务超时(120秒),结果尚未确认"
|
||||
: stage === "poll"
|
||||
? `AOS查询任务超时,结果尚未确认(任务 ${providerTaskId})`
|
||||
: `AOS结果下载超时,任务已完成(任务 ${providerTaskId})`;
|
||||
return { success: false, error: message };
|
||||
}
|
||||
logger.warn("aos_provider_request_error", error);
|
||||
return { success: false, error: error instanceof Error ? error.message : "未知错误" };
|
||||
logger.warn("aos_provider_request_error", error, { requestId: config.requestId, stage, taskId: providerTaskId });
|
||||
const detail = error instanceof Error ? error.message : "未知错误";
|
||||
return { success: false, error: stage === "create"
|
||||
? `AOS创建任务连接失败,结果尚未确认:${detail}`
|
||||
: stage === "poll"
|
||||
? `AOS查询任务连接失败,结果尚未确认(任务 ${providerTaskId}):${detail}`
|
||||
: `AOS结果下载连接失败,任务已完成(任务 ${providerTaskId}):${detail}` };
|
||||
}
|
||||
}
|
||||
|
||||
@ -601,6 +660,7 @@ export async function executeRmbgJob(
|
||||
params: ExecuteRmbgJobParams
|
||||
): Promise<ExecuteRmbgJobResult> {
|
||||
const {
|
||||
requestId,
|
||||
userId,
|
||||
imageBuffer,
|
||||
imageBase64 = imageBuffer.toString("base64"),
|
||||
@ -657,6 +717,8 @@ export async function executeRmbgJob(
|
||||
foregroundType: foregroundType ?? config.aosForegroundType ?? "",
|
||||
crop: config.aosCrop === 1 ? 1 : 0,
|
||||
format: config.aosFormat === "jpg" ? "jpg" : "png",
|
||||
sourceImageUrl,
|
||||
requestId,
|
||||
});
|
||||
|
||||
if (!result.success || !result.imageBuffer) {
|
||||
|
||||
@ -128,6 +128,7 @@ async function executeForTarget(
|
||||
if (command.capabilityId === "image.remove_background") {
|
||||
const imageBuffer = await fetchImageBufferFromUrl(target.sourceImageUrl);
|
||||
const result = await executeRmbgJob({
|
||||
requestId: command.requestId,
|
||||
userId: params.userId,
|
||||
imageBuffer,
|
||||
sourceImageUrl: target.sourceImageUrl,
|
||||
|
||||
@ -6,8 +6,9 @@ const IMAGE_PROXY_PATH = "/api/image-proxy";
|
||||
export function buildImageFallbackUrl(value: string | null | undefined): string {
|
||||
const source = value || "";
|
||||
const legacy = normalizeLegacyAliyunStorageUrl(source);
|
||||
if (!legacy) return source;
|
||||
const proxy = buildImageProxyUrl(legacy);
|
||||
const modelImage = isAlibabaModelImageUrl(source);
|
||||
if (!legacy && !modelImage) return source;
|
||||
const proxy = buildImageProxyUrl(legacy || source, modelImage ? { width: 960, quality: 86, format: "webp" } : {});
|
||||
return typeof window === "undefined" ? proxy : new URL(proxy, window.location.origin).toString();
|
||||
}
|
||||
|
||||
@ -20,6 +21,26 @@ export type ImageProxyOptions = {
|
||||
delivery?: "display" | "proxy" | "original";
|
||||
};
|
||||
|
||||
export function getFullscreenPreviewSize({
|
||||
imageWidth,
|
||||
imageHeight,
|
||||
viewportWidth,
|
||||
viewportHeight,
|
||||
pixelRatio = 1,
|
||||
}: {
|
||||
imageWidth: number;
|
||||
imageHeight: number;
|
||||
viewportWidth: number;
|
||||
viewportHeight: number;
|
||||
pixelRatio?: number;
|
||||
}) {
|
||||
const ratio = imageWidth > 0 && imageHeight > 0 ? imageWidth / imageHeight : 1;
|
||||
const displayWidth = Math.min(viewportWidth * 0.95, viewportHeight * 0.95 * ratio);
|
||||
const requiredWidth = displayWidth * Math.max(1, pixelRatio || 1);
|
||||
const requestWidth = [640, 960, 1280, 1600, 2048, 2560, 3200, 4096].find((width) => width >= requiredWidth) || 4096;
|
||||
return { displayWidth, requestWidth };
|
||||
}
|
||||
|
||||
/** Preserve the actual response format when naming an original download. */
|
||||
export function getImageDownloadExtension(contentType: string) {
|
||||
const mime = contentType.split(";")[0]?.trim().toLowerCase();
|
||||
@ -70,6 +91,15 @@ function isAliyunOssImageHost(hostname: string): boolean {
|
||||
return normalized.endsWith(".aliyuncs.com") && normalized.includes(".oss-");
|
||||
}
|
||||
|
||||
/** Model result buckets allow downloading objects but deny OSS image processing. */
|
||||
export function isAlibabaModelImageUrl(value: string): boolean {
|
||||
try {
|
||||
return /^dashscope(?:-[a-z0-9-]+)?\.oss-[a-z0-9-]+\.aliyuncs\.com$/i.test(new URL(value).hostname);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isTrustedDirectStorageImageHost(hostname: string): boolean {
|
||||
const normalized = hostname.trim().toLowerCase();
|
||||
let configuredCdnHost = "";
|
||||
@ -211,7 +241,7 @@ export function buildImageProxyUrl(url: string, options: ImageProxyOptions = {})
|
||||
return trustedDirectStorageUrl;
|
||||
}
|
||||
|
||||
if (options.delivery !== "proxy" && !normalizeLegacyAliyunStorageUrl(source)) {
|
||||
if (options.delivery !== "proxy" && !normalizeLegacyAliyunStorageUrl(source) && !isAlibabaModelImageUrl(source)) {
|
||||
const directDisplayUrl = resolveAliyunOssDisplayUrl(source, options);
|
||||
if (directDisplayUrl) {
|
||||
return directDisplayUrl;
|
||||
|
||||
@ -231,6 +231,24 @@ export function getRequestFailureDetails(
|
||||
if (isGatewayResponseTimeout(error)) {
|
||||
return detail("RESULT_UNCONFIRMED", "模型服务响应超时(HTTP 524),生成结果尚未确认。", "请先查看历史记录,避免重复提交。", "unknown");
|
||||
}
|
||||
if (/AOS创建任务超时/.test(text)) {
|
||||
return detail("RMBG_CREATE_TIMEOUT", "抠图服务创建任务超时(120秒),结果尚未确认。", "请先查看原任务或联系管理员核对;不要连续点击,以免重复处理。", "unknown");
|
||||
}
|
||||
if (/AOS创建任务连接失败/.test(text)) {
|
||||
return detail("RMBG_CREATE_CONNECTION_FAILED", "抠图服务创建任务时连接中断,结果尚未确认。", "请先查看原任务或联系管理员核对;不要连续点击,以免重复处理。", "unknown");
|
||||
}
|
||||
if (/AOS查询任务连接失败/.test(text)) {
|
||||
return detail("RMBG_POLL_CONNECTION_FAILED", "抠图服务查询任务时连接中断,原任务可能仍在处理。", "请保留当前页面并联系管理员核对原任务,避免重新提交。", "unknown");
|
||||
}
|
||||
if (/AOS查询任务超时/.test(text)) {
|
||||
return detail("RMBG_POLL_TIMEOUT", "抠图服务查询任务超时,原任务可能仍在处理。", "请保留当前页面并联系管理员核对原任务,避免重新提交。", "unknown");
|
||||
}
|
||||
if (/AOS结果下载连接失败/.test(text)) {
|
||||
return detail("RMBG_RESULT_DOWNLOAD_CONNECTION_FAILED", "抠图已完成,但结果图片传输中断。", "请联系管理员按请求编号取回原任务结果,避免重复抠图。", "unknown");
|
||||
}
|
||||
if (/AOS结果下载超时/.test(text)) {
|
||||
return detail("RMBG_RESULT_DOWNLOAD_TIMEOUT", "抠图已完成,但结果图片下载超时。", "请联系管理员按请求编号取回原任务结果,避免重复抠图。", "unknown");
|
||||
}
|
||||
if ((isRecord(error) && error.providerOutcomeUnknown === true) || /结果(?:尚)?未确认|结果暂未确认|request_outcome_unknown|任务执行中断|may still be running/i.test(text)) {
|
||||
return detail("RESULT_UNCONFIRMED", "任务结果尚未确认,可能仍在处理。", "请先查看原任务或历史记录;持续没有结果时联系管理员,避免重复生成。", "unknown");
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@ import { defineConfig } from "@playwright/test";
|
||||
export default defineConfig({
|
||||
testDir: "./tests",
|
||||
testMatch: [
|
||||
/routes\/rmbg-delivery\.test\.ts/,
|
||||
/routes\/legacy-oss-recovery\.test\.ts/,
|
||||
/routes\/retired-storage\.test\.ts/,
|
||||
/routes\/original-image-download\.test\.ts/,
|
||||
|
||||
@ -53,6 +53,7 @@ export function serverLoader(mocks: Record<string, unknown>, env: Record<string,
|
||||
ReadableStream,
|
||||
Headers,
|
||||
Blob,
|
||||
FormData,
|
||||
Request,
|
||||
Date: mocks.Date || Date,
|
||||
document: mocks.document,
|
||||
|
||||
@ -2,9 +2,77 @@ import { expect, test } from "@playwright/test";
|
||||
import { NextRequest } from "next/server";
|
||||
import sharp from "sharp";
|
||||
import { GET } from "@/app/api/image-proxy/route";
|
||||
import { buildImageProxyUrl, getImageDownloadExtension } from "@/lib/image-delivery";
|
||||
import { buildImageProxyUrl, getFullscreenPreviewSize, getImageDownloadExtension } from "@/lib/image-delivery";
|
||||
import { serverLoader } from "../helpers/canvas-download-server-loader";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
test.describe("Qiniu image delivery", () => {
|
||||
test("model result buckets use our thumbnail endpoint without forbidden OSS transforms", () => {
|
||||
const source = "https://dashscope-a717.oss-accelerate.aliyuncs.com/output.png";
|
||||
const preview = new URL(buildImageProxyUrl(source, { width: 960, format: "webp" }), "https://app.example");
|
||||
expect(preview.pathname).toBe("/api/image-proxy");
|
||||
expect(preview.searchParams.get("url")).toBe(source);
|
||||
expect(preview.searchParams.has("x-oss-process")).toBe(false);
|
||||
expect(buildImageProxyUrl("https://other-bucket.oss-cn-shanghai.aliyuncs.com/image.png", { width: 960 })).toContain("x-oss-process=");
|
||||
});
|
||||
|
||||
test("a completed archive serves old model-result references from Qiniu immediately", async () => {
|
||||
const source = "https://dashscope-a717.oss-accelerate.aliyuncs.com/archived.png";
|
||||
const route = serverLoader({
|
||||
"next/server": { NextResponse },
|
||||
"@/lib/storage/image-archive-db": { getArchivedImageUrlMappings: async () => ({ [source]: "https://yybb.top/archived.png" }) },
|
||||
fetch: () => { throw new Error("Must use the completed archive"); },
|
||||
})("app/api/image-proxy/route.ts");
|
||||
const request = new URL("https://app.example/api/image-proxy");
|
||||
request.searchParams.set("url", source); request.searchParams.set("w", "960"); request.searchParams.set("f", "webp");
|
||||
const response = await route.GET(new NextRequest(request, { headers: { "sec-fetch-dest": "image" } }));
|
||||
expect(response.status).toBe(307);
|
||||
expect(response.headers.get("location")).toBe("https://yybb.top/archived.png?imageView2/2/w/960/format/webp/q/82");
|
||||
});
|
||||
|
||||
test("unarchived model previews share one original fetch with archiving and return resized WebP", async () => {
|
||||
const source = `https://dashscope-a717.oss-accelerate.aliyuncs.com/${crypto.randomUUID()}.png`;
|
||||
const original = await sharp({ create: { width: 1024, height: 1024, channels: 3, background: "#345678" } }).png().toBuffer();
|
||||
let requests = 0;
|
||||
const load = serverLoader({
|
||||
"next/server": { NextResponse },
|
||||
"@/lib/storage/image-archive-db": { getArchivedImageUrlMappings: async () => ({}) },
|
||||
fetch: async (url: string) => {
|
||||
expect(url).toBe(source); requests++;
|
||||
await new Promise(resolve => setTimeout(resolve, 30));
|
||||
return new Response(original, { headers: { "content-type": "image/png" } });
|
||||
},
|
||||
});
|
||||
const route = load("app/api/image-proxy/route.ts");
|
||||
const archiveRead = load("lib/storage/image-byte-cache.ts").fetchImageBytes(source);
|
||||
const responses = await Promise.all([100, 200].map(width => {
|
||||
const request = new URL("https://app.example/api/image-proxy");
|
||||
request.searchParams.set("url", source); request.searchParams.set("w", String(width)); request.searchParams.set("f", "webp");
|
||||
return route.GET(new NextRequest(request, { headers: { "sec-fetch-dest": "image" } }));
|
||||
}));
|
||||
expect((await archiveRead).buffer.equals(original)).toBe(true);
|
||||
expect(requests).toBe(1);
|
||||
for (let i = 0; i < responses.length; i++) {
|
||||
expect(responses[i].status).toBe(200);
|
||||
expect(responses[i].headers.get("content-type")).toBe("image/webp");
|
||||
expect((await sharp(Buffer.from(await responses[i].arrayBuffer())).metadata()).width).toBe([100, 200][i]);
|
||||
}
|
||||
});
|
||||
test("sizes a fullscreen square to its visible height and reuses the chat preview on standard density screens", () => {
|
||||
const size = getFullscreenPreviewSize({ imageWidth: 2048, imageHeight: 2048, viewportWidth: 1657, viewportHeight: 884 });
|
||||
expect(size.displayWidth).toBeCloseTo(839.8);
|
||||
expect(size.requestWidth).toBe(960);
|
||||
expect(buildImageProxyUrl("https://yybb.top/a.png", { width: size.requestWidth, quality: 86, format: "webp" }))
|
||||
.toBe(buildImageProxyUrl("https://yybb.top/a.png", { width: 960, quality: 86, format: "webp" }));
|
||||
});
|
||||
|
||||
test("preserves screen density and image aspect ratio without requesting oversized fixed previews", () => {
|
||||
expect(getFullscreenPreviewSize({ imageWidth: 2048, imageHeight: 2048, viewportWidth: 1657, viewportHeight: 884, pixelRatio: 2 }).requestWidth).toBe(2048);
|
||||
const portrait = getFullscreenPreviewSize({ imageWidth: 1000, imageHeight: 2000, viewportWidth: 1440, viewportHeight: 900, pixelRatio: 2 });
|
||||
expect(portrait.displayWidth).toBeCloseTo(427.5);
|
||||
expect(portrait.requestWidth).toBe(960);
|
||||
expect(getFullscreenPreviewSize({ imageWidth: 4000, imageHeight: 1000, viewportWidth: 5000, viewportHeight: 2000, pixelRatio: 2 }).requestWidth).toBe(4096);
|
||||
});
|
||||
test("reports a timeout while reading image bytes as a retryable response", async () => {
|
||||
const previousFetch = globalThis.fetch;
|
||||
globalThis.fetch = async () => new Response(new ReadableStream({
|
||||
|
||||
@ -38,7 +38,7 @@ test("legacy display URLs go through archive resolution while other Alibaba buck
|
||||
const url = buildImageProxyUrl(legacy, { width: 400 });
|
||||
expect(url).toMatch(/^\/api\/image-proxy\?/);
|
||||
expect(new URL(url, "https://app.example").searchParams.get("url")).toBe(legacy);
|
||||
expect(buildImageProxyUrl("https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/result.png", { width: 400 })).toContain("x-oss-process=");
|
||||
expect(buildImageProxyUrl("https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/result.png", { width: 400 })).toMatch(/^\/api\/image-proxy\?/);
|
||||
});
|
||||
|
||||
test("browser image fallbacks remain on one stable archive URL instead of retrying the old source", () => {
|
||||
|
||||
119
tests/routes/rmbg-delivery.test.ts
Normal file
119
tests/routes/rmbg-delivery.test.ts
Normal file
@ -0,0 +1,119 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
import sharp from "sharp";
|
||||
import { serverLoader } from "../helpers/canvas-download-server-loader";
|
||||
import { getRequestFailureDetails } from "@/lib/request-error";
|
||||
|
||||
const cdn = "https://scqnycdn.jiansun.vip";
|
||||
|
||||
function rmbgLoader(fetch: typeof globalThis.fetch, timer?: typeof setTimeout) {
|
||||
return serverLoader({
|
||||
"@/lib/db/queries": { getSystemSetting: async () => ({ value: { provider: "aoscdn", aosApiKey: "test-key" } }) },
|
||||
"@/lib/db": { db: {} },
|
||||
"@/lib/db/schema": { generatedImage: {} },
|
||||
"@/lib/storage/service": { uploadFile: async (name: string) => ({ url: `${cdn}/${name}` }) },
|
||||
fetch,
|
||||
setTimeout: timer || ((callback: () => void, ms: number) => setTimeout(callback, ms <= 2000 ? 0 : ms)),
|
||||
}, { NEXT_PUBLIC_CANVAS_CDN_ORIGIN: cdn })("lib/ai/rmbg/service.ts");
|
||||
}
|
||||
|
||||
test("AOS uses a public Qiniu original URL without uploading the image file again", async () => {
|
||||
const image = await sharp({ create: { width: 1024, height: 768, channels: 3, background: "#abcdef" } }).png().toBuffer();
|
||||
let creates = 0;
|
||||
const source = `${cdn}/uploads/original.png`;
|
||||
const service = rmbgLoader(async (input, options) => {
|
||||
const url = String(input);
|
||||
if (options?.method === "POST") {
|
||||
creates++;
|
||||
const form = options.body as FormData;
|
||||
expect(form.get("image_url")).toBe(source);
|
||||
expect(form.has("image_file")).toBe(false);
|
||||
expect(form.get("sync")).toBe("0");
|
||||
return Response.json({ data: { task_id: "task-url" } });
|
||||
}
|
||||
if (url.endsWith("/task-url")) return Response.json({ data: { state: 1, image: "https://output.example/image.png" } });
|
||||
return new Response(image, { headers: { "content-type": "image/png" } });
|
||||
});
|
||||
const result = await service.executeRmbgJob({ userId: "test", imageBuffer: image, sourceImageUrl: source, skipGallerySave: true });
|
||||
expect(creates).toBe(1);
|
||||
expect(result.provider).toBe("aoscdn");
|
||||
expect(result.original_url).toContain(cdn);
|
||||
});
|
||||
|
||||
test("oversized images and non-CDN sources keep the normalized file upload", async () => {
|
||||
for (const [width, source] of [[5000, `${cdn}/large.png`], [1000, "http://127.0.0.1/private.png"], [1000, "https://other.example/image.png"]] as const) {
|
||||
const image = await sharp({ create: { width, height: 20, channels: 3, background: "#abcdef" } }).png().toBuffer();
|
||||
const service = rmbgLoader(async (input, options) => {
|
||||
if (options?.method === "POST") {
|
||||
const form = options.body as FormData;
|
||||
expect(form.has("image_url")).toBe(false);
|
||||
const file = form.get("image_file") as File;
|
||||
expect((await sharp(Buffer.from(await file.arrayBuffer())).metadata()).width).toBe(Math.min(width, 4096));
|
||||
return Response.json({ data: { task_id: "task-file" } });
|
||||
}
|
||||
if (String(input).endsWith("/task-file")) return Response.json({ data: { state: 1, image: "https://output.example/image.png" } });
|
||||
return new Response(image, { headers: { "content-type": "image/png" } });
|
||||
});
|
||||
await service.executeRmbgJob({ userId: "test", imageBuffer: image, sourceImageUrl: source, skipGallerySave: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a create timeout preserves its cause and never creates another paid task", async () => {
|
||||
const image = await sharp({ create: { width: 16, height: 16, channels: 3, background: "white" } }).png().toBuffer();
|
||||
let creates = 0;
|
||||
let abort: Error;
|
||||
const service = rmbgLoader(async () => { creates++; throw abort; });
|
||||
abort = new service.RmbgServiceError("request timed out");
|
||||
abort.name = "AbortError";
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await service.executeRmbgJob({ userId: "test", imageBuffer: image, sourceImageUrl: `${cdn}/source.png`, skipGallerySave: true });
|
||||
} catch (error) { failure = error as Error; }
|
||||
expect(creates).toBe(1);
|
||||
expect(failure?.message).toContain("AOS创建任务超时(120秒)");
|
||||
expect(getRequestFailureDetails(failure)).toMatchObject({ code: "RMBG_CREATE_TIMEOUT", outcome: "unknown" });
|
||||
});
|
||||
|
||||
test("poll and result download timeouts retain their original task and distinct advice", () => {
|
||||
const poll = getRequestFailureDetails("抠图处理失败:AOS查询任务超时,结果尚未确认(任务 task-1)");
|
||||
const download = getRequestFailureDetails("抠图处理失败:AOS结果下载超时,任务已完成(任务 task-1)");
|
||||
expect(poll).toMatchObject({ code: "RMBG_POLL_TIMEOUT", outcome: "unknown" });
|
||||
expect(download).toMatchObject({ code: "RMBG_RESULT_DOWNLOAD_TIMEOUT", outcome: "unknown" });
|
||||
expect(download.recommendation).toContain("取回原任务结果");
|
||||
});
|
||||
|
||||
test("network and body interruptions retry only the original task reads", async () => {
|
||||
const image = await sharp({ create: { width: 32, height: 32, channels: 4, background: "#abcdef00" } }).png().toBuffer();
|
||||
let creates = 0, polls = 0, downloads = 0;
|
||||
let networkError: Error;
|
||||
const service = rmbgLoader(async (input, options) => {
|
||||
if (options?.method === "POST") { creates++; return Response.json({ data: { task_id: "original-task" } }); }
|
||||
if (String(input).endsWith("/original-task")) {
|
||||
if (++polls === 1) throw networkError;
|
||||
return Response.json({ data: { state: 1, image: "https://output.example/original.png" } });
|
||||
}
|
||||
if (++downloads === 1) return new Response(new ReadableStream({ start(controller) { controller.error(networkError); } }));
|
||||
return new Response(image, { headers: { "content-type": "image/png" } });
|
||||
});
|
||||
networkError = new service.RmbgServiceError("fetch failed"); networkError.name = "TypeError";
|
||||
const result = await service.executeRmbgJob({ userId: "test", imageBuffer: image, sourceImageUrl: `${cdn}/source.png`, skipGallerySave: true });
|
||||
expect(result.original_url).toContain(cdn);
|
||||
expect({ creates, polls, downloads }).toEqual({ creates: 1, polls: 2, downloads: 2 });
|
||||
});
|
||||
|
||||
test("exhausted result reads preserve the completed task and never re-create it", async () => {
|
||||
const image = await sharp({ create: { width: 16, height: 16, channels: 3, background: "white" } }).png().toBuffer();
|
||||
let creates = 0, downloads = 0;
|
||||
let networkError: Error;
|
||||
const service = rmbgLoader(async (input, options) => {
|
||||
if (options?.method === "POST") { creates++; return Response.json({ data: { task_id: "completed-task" } }); }
|
||||
if (String(input).endsWith("/completed-task")) return Response.json({ data: { state: 1, image: "https://output.example/original.png" } });
|
||||
downloads++; throw networkError;
|
||||
});
|
||||
networkError = new service.RmbgServiceError("fetch failed"); networkError.name = "TypeError";
|
||||
let failure: Error | undefined;
|
||||
try { await service.executeRmbgJob({ userId: "test", imageBuffer: image, sourceImageUrl: `${cdn}/source.png`, skipGallerySave: true }); }
|
||||
catch (error) { failure = error as Error; }
|
||||
expect({ creates, downloads }).toEqual({ creates: 1, downloads: 3 });
|
||||
expect(failure?.message).toContain("completed-task");
|
||||
expect(getRequestFailureDetails(failure)).toMatchObject({ code: "RMBG_RESULT_DOWNLOAD_CONNECTION_FAILED", outcome: "unknown" });
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user