Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

15.0 KB
Raw Blame
import { type LobeChatDatabase } from '@lobechat/database';
import { parseDataUri } from '@lobechat/model-runtime';
import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
import debug from 'debug';
import { sha256 } from 'js-sha256';
import mime from 'mime';
import { IMAGE_GENERATION_CONFIG } from 'model-bank';
import { nanoid } from 'nanoid';
import sharp from 'sharp';

import { GenerationTopicModel } from '@/database/models/generationTopic';
import { FileService } from '@/server/services/file';
import { calculateThumbnailDimensions } from '@/utils/number';
import { getYYYYmmddHHMMss } from '@/utils/time';
import { inferFileExtensionFromImageUrl } from '@/utils/url';

const log = debug('lobe-image:generation-service');

/**
 * Fetch image buffer and MIME type from URL or base64 data
 * @param url - Image URL or base64 data URI
 * @param fetchHeaders - Optional headers for authentication
 * @returns Object containing buffer and MIME type
 */
export async function fetchImageFromUrl(
  url: string,
  fetchHeaders?: Record<string, string>,
): Promise<{
  buffer: Buffer;
  mimeType: string;
}> {
  if (url.startsWith('data:')) {
    log('Data URI length:', url.length);

    log('parseDataUri: start');
    const { base64, mimeType, type } = parseDataUri(url);
    log('parseDataUri: done, base64 length:', base64?.length, 'mimeType:', mimeType);

    if (type !== 'base64' || !base64 || !mimeType) {
      throw new Error(`Invalid data URI format: ${url}`);
    }

    try {
      log('Buffer.from base64: start');
      const buffer = Buffer.from(base64, 'base64');
      log('Buffer.from base64: done, buffer size:', buffer.length);
      return { buffer, mimeType };
    } catch (error) {
      throw new Error(
        `Failed to decode base64 data: ${error instanceof Error ? error.message : String(error)}`,
        { cause: error },
      );
    }
  } else {
    // Use ssrfSafeFetch (not raw global fetch): url can be user-supplied (e.g. the
    // updateTopicCover coverUrl), so a raw fetch would let an authenticated user make the
    // server request arbitrary internal hosts / cloud metadata (SSRF) — image-typed responses
    // are read and returned, other responses leak status/statusText for blind probing.
    // ssrfSafeFetch blocks private/link-local IPs at connect time and on every redirect hop.
    // See GHSA-53h9-fmjf-frwr / #16536.
    return downloadWithRetry(url, fetchHeaders);
  }
}

/**
 * Delays before each retry of a remote image download. Providers such as xAI return a
 * short-lived CDN URL after the generation is already billed upstream, so a single reset
 * connection (ECONNRESET while reading the body) would otherwise discard a paid image.
 */
export const IMAGE_DOWNLOAD_RETRY_DELAYS_MS = [500, 1500];

const isRetryableStatus = (status: number) => status === 408 || status === 429 || status >= 500;

/**
 * Download through ssrfSafeFetch, retrying transient failures: thrown network/body-read
 * errors and 408/429/5xx responses. SSRF blocks and other 4xx responses are final.
 */
const downloadWithRetry = async (
  url: string,
  fetchHeaders?: Record<string, string>,
): Promise<{ buffer: Buffer; mimeType: string }> => {
  for (let attempt = 0; ; attempt++) {
    const canRetry = attempt < IMAGE_DOWNLOAD_RETRY_DELAYS_MS.length;
    let response: Response;

    try {
      response = await ssrfSafeFetch(url, { headers: fetchHeaders });
      // ssrfSafeFetch resolves at the headers, so a reset while downloading the body
      // surfaces here and must stay inside the retry.
      if (response.ok) {
        const buffer = Buffer.from(await response.arrayBuffer());
        const mimeType = response.headers.get('content-type') || 'application/octet-stream';
        return { buffer, mimeType };
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      if (message.startsWith('SSRF blocked')) throw error;

      if (!canRetry) {
        // Keep the transport detail in `cause` only: body-read failures surface as
        // "...: aborted", which the async image task would misreport as TaskTimeout.
        throw new Error(
          `Failed to fetch image from ${url} after ${attempt + 1} attempts: network error`,
          { cause: error },
        );
      }

      log('Image download failed, retrying (attempt %d): %s', attempt + 1, message);
      await new Promise((resolve) => setTimeout(resolve, IMAGE_DOWNLOAD_RETRY_DELAYS_MS[attempt]));
      continue;
    }

    // The error body is never read; release its connection.
    await response.body?.cancel().catch(() => {});
    if (!canRetry || !isRetryableStatus(response.status)) {
      throw new Error(
        `Failed to fetch image from ${url}: ${response.status} ${response.statusText}`,
      );
    }

    log('Image download returned %d, retrying (attempt %d)', response.status, attempt + 1);
    await new Promise((resolve) => setTimeout(resolve, IMAGE_DOWNLOAD_RETRY_DELAYS_MS[attempt]));
  }
};

interface ImageForGeneration {
  buffer: Buffer;
  extension: string;
  hash: string;
  height: number;
  mime: string;
  size: number;
  width: number;
}

/**
 * Image generation service
 * Handles conversion, upload and cover creation for AI-generated images
 */
export class GenerationService {
  private fileService: FileService;
  private generationTopicModel: GenerationTopicModel;

  constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
    this.fileService = new FileService(db, userId, workspaceId);
    this.generationTopicModel = new GenerationTopicModel(db, userId, workspaceId);
  }

  /**
   * Generate width 512px image as thumbnail when width > 512, end with _512.webp
   */
  async transformImageForGeneration(
    url: string,
    fetchHeaders?: Record<string, string>,
  ): Promise<{
    image: ImageForGeneration;
    thumbnailImage: ImageForGeneration;
  }> {
    log('Starting image transformation for:', url.startsWith('data:') ? 'base64 data' : url);

    // Fetch image buffer and MIME type using utility function
    log('fetchImageFromUrl: start');
    const { buffer: originalImageBuffer, mimeType: originalMimeType } = await fetchImageFromUrl(
      url,
      fetchHeaders,
    );
    log('fetchImageFromUrl: done, buffer size:', originalImageBuffer.length);

    // Calculate hash for original image
    log('sha256: start');
    const originalHash = sha256(originalImageBuffer);
    log('sha256: done');

    log('sharp metadata: start');
    const sharpInstance = sharp(originalImageBuffer);
    const { format, width, height } = await sharpInstance.metadata();
    log('Image metadata:', { format, height, width });

    if (!width || !height) {
      throw new Error(`Invalid image format: ${format}, url: ${url}`);
    }

    const {
      shouldResize: shouldResizeBySize,
      thumbnailWidth,
      thumbnailHeight,
    } = calculateThumbnailDimensions(width, height);
    const shouldResize = shouldResizeBySize || format !== 'webp';

    log('Thumbnail processing decision:', {
      format,
      shouldResize,
      shouldResizeBySize,
      thumbnailHeight,
      thumbnailWidth,
    });

    const thumbnailBuffer = shouldResize
      ? await sharpInstance.resize(thumbnailWidth, thumbnailHeight).webp().toBuffer()
      : originalImageBuffer;

    // Calculate hash for thumbnail
    const thumbnailHash = sha256(thumbnailBuffer);

    log('Image transformation completed successfully');

    // Determine extension using url utility
    let extension: string;
    if (url.startsWith('data:')) {
      const mimeExtension = mime.getExtension(originalMimeType);
      if (!mimeExtension) {
        throw new Error(`Unable to determine file extension for MIME type: ${originalMimeType}`);
      }
      extension = mimeExtension;
    } else {
      // Try to get extension from URL path first
      extension = inferFileExtensionFromImageUrl(url);

      // For ComfyUI URLs, check filename in query parameters
      if (!extension && url.includes('filename=')) {
        try {
          const urlObj = new URL(url);
          const filename = urlObj.searchParams.get('filename');
          if (filename) {
            extension = inferFileExtensionFromImageUrl(filename);
          }
        } catch {
          // Ignore URL parsing errors
        }
      }

      // If still no extension, try to get from MIME type
      if (!extension && originalMimeType && originalMimeType !== 'application/octet-stream') {
        const mimeExtension = mime.getExtension(originalMimeType);
        if (mimeExtension) {
          extension = mimeExtension;
        }
      }

      if (!extension) {
        throw new Error(`Unable to determine file extension from URL: ${url}`);
      }
    }

    return {
      image: {
        buffer: originalImageBuffer,
        extension,
        hash: originalHash,
        height,
        mime: originalMimeType,
        size: originalImageBuffer.length,
        width,
      },
      thumbnailImage: {
        buffer: thumbnailBuffer,
        extension: 'webp',
        hash: thumbnailHash,
        height: thumbnailHeight,
        mime: 'image/webp',
        size: thumbnailBuffer.length,
        width: thumbnailWidth,
      },
    };
  }

  async uploadImageForGeneration(image: ImageForGeneration, thumbnail: ImageForGeneration) {
    log('Starting image upload for generation');

    const generationImagesFolder = 'generations/images';
    const uuid = nanoid();
    const dateTime = getYYYYmmddHHMMss(new Date());
    const imageKey = `${generationImagesFolder}/${uuid}_${image.width}x${image.height}_${dateTime}_raw.${image.extension}`;
    const thumbnailKey = `${generationImagesFolder}/${uuid}_${thumbnail.width}x${thumbnail.height}_${dateTime}_thumb.${thumbnail.extension}`;

    log('Generated paths:', { imagePath: imageKey, thumbnailPath: thumbnailKey });

    // Check if image and thumbnail buffers are identical
    const isIdenticalBuffer = image.buffer.equals(thumbnail.buffer);
    log('Buffer comparison:', {
      imageSize: image.buffer.length,
      isIdenticalBuffer,
      thumbnailSize: thumbnail.buffer.length,
    });

    if (isIdenticalBuffer) {
      log('Buffers are identical, uploading single image');
      // If buffers are identical, only upload once
      const result = await this.fileService.uploadMedia(imageKey, image.buffer);
      log('Single image uploaded successfully:', result.key);
      // Use the same key for both image and thumbnail
      return {
        imageUrl: result.key,
        thumbnailImageUrl: result.key,
      };
    } else {
      log('Buffers are different, uploading both images');
      // If buffers are different, upload both
      const [imageResult, thumbnailResult] = await Promise.all([
        this.fileService.uploadMedia(imageKey, image.buffer),
        this.fileService.uploadMedia(thumbnailKey, thumbnail.buffer),
      ]);

      log('Both images uploaded successfully:', {
        imageUrl: imageResult.key,
        thumbnailImageUrl: thumbnailResult.key,
      });

      return {
        imageUrl: imageResult.key,
        thumbnailImageUrl: thumbnailResult.key,
      };
    }
  }

  /**
   * Create a cover image from a given URL and upload
   * @param coverUrl - The source image URL (can be base64 or HTTP URL)
   * @returns The key of the uploaded cover image
   */
  async createCoverFromUrl(coverUrl: string): Promise<string> {
    log('Creating cover image from URL:', coverUrl.startsWith('data:') ? 'base64 data' : coverUrl);

    // Fetch image buffer using utility function
    const { buffer } = await fetchImageFromUrl(coverUrl);

    return this.createCoverFromBuffer(buffer);
  }

  /**
   * Fill an empty topic cover from a generated asset stored in S3.
   *
   * Runs on the server success path so topics get a cover no matter where the
   * generation was started (image/video page, agent tools) or whether any
   * client is still polling. Failures are logged and swallowed: the generation
   * itself already succeeded.
   *
   * @param topicId - The generation topic to fill
   * @param sourceKey - S3 key of the generated image or video thumbnail
   */
  async ensureTopicCover(topicId: string, sourceKey: string): Promise<void> {
    let coverKey: string | undefined;
    try {
      const topic = await this.generationTopicModel.findById(topicId);
      if (!topic || topic.coverUrl) return;

      // Read the object directly instead of fetching its URL, which may be an
      // internal S3 endpoint rejected by the SSRF-safe fetch in self-hosted setups.
      const source = await this.fileService.getFileByteArray(sourceKey);
      coverKey = await this.createCoverFromBuffer(Buffer.from(source));

      const updated = await this.generationTopicModel.updateCoverIfEmpty(topicId, coverKey);
      if (updated) return;

      log('Topic %s got a cover from a concurrent generation, removing %s', topicId, coverKey);
    } catch (error) {
      console.error('[generation] Failed to set topic cover:', error);
      if (!coverKey) return;

      // The update may have committed before failing (e.g. the connection dropped
      // before returning). Deleting a committed cover would leave a broken
      // reference that later generations never repair, so only delete when the
      // topic provably does not use it; keep the object if that cannot be checked.
      try {
        const topic = await this.generationTopicModel.findById(topicId);
        if (topic?.coverUrl === coverKey) return;
      } catch (checkError) {
        console.error('[generation] Failed to verify topic cover, keeping upload:', checkError);
        return;
      }
    }

    // The uploaded cover was not saved on the topic; delete it so it is not orphaned
    try {
      await this.fileService.deleteFile(coverKey);
    } catch (error) {
      console.error('[generation] Failed to delete unused topic cover:', error);
    }
  }

  private async createCoverFromBuffer(originalImageBuffer: Buffer): Promise<string> {
    // Get image metadata to calculate proper cover dimensions
    const sharpInstance = sharp(originalImageBuffer);
    const { width, height } = await sharpInstance.metadata();

    if (!width || !height) {
      throw new Error('Invalid image format for cover creation');
    }

    // Calculate cover dimensions maintaining aspect ratio with configurable max size
    const { thumbnailWidth, thumbnailHeight } = calculateThumbnailDimensions(
      width,
      height,
      IMAGE_GENERATION_CONFIG.COVER_MAX_SIZE,
    );

    log('Processing cover image with dimensions:', {
      cover: { height: thumbnailHeight, width: thumbnailWidth },
      original: { height, width },
    });

    const coverBuffer = await sharpInstance
      .resize(thumbnailWidth, thumbnailHeight)
      .webp()
      .toBuffer();

    log('Cover image processed, final size:', coverBuffer.length);

    // Upload using FileService
    const coverFolder = 'generations/covers';
    const uuid = nanoid();
    const dateTime = getYYYYmmddHHMMss(new Date());
    const coverKey = `${coverFolder}/${uuid}_${thumbnailWidth}x${thumbnailHeight}_${dateTime}_cover.webp`;

    log('Uploading cover image:', coverKey);
    const result = await this.fileService.uploadMedia(coverKey, coverBuffer);

    log('Cover image uploaded successfully:', result.key);
    return result.key;
  }
}