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.3 KB
Raw Blame
import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';
import { parseDataUri } from '@lobechat/model-runtime/utils/uriParser';
import { uuid } from '@lobechat/utils';
import dayjs from 'dayjs';

import { fileEnv } from '@/envs/file';
import { scopedLambdaClient } from '@/libs/trpc/client';
import type { FileMetadata, UploadBase64ToS3Result } from '@/types/files';
import type { FileUploadState, FileUploadStatus } from '@/types/files/upload';

import { hashFile } from './hashFile';

export const UPLOAD_NETWORK_ERROR = 'NetWorkError';

const MAX_MULTIPART_PARTS = 10_000;
const MULTIPART_PART_SIZE = 32 * 1024 * 1024;
const MULTIPART_UPLOAD_THRESHOLD = 64 * 1024 * 1024;
/** One part is sent at most this many times when storage fails it transiently. */
const MULTIPART_PART_MAX_ATTEMPTS = 3;
const MULTIPART_PART_RETRY_DELAY_MS = 1000;

/** S3 error codes that only mean "try again", returned with a 4xx status. */
const RETRYABLE_STORAGE_ERROR_CODES = new Set([
  'RequestTimeout',
  'RequestTimeTooSkewed',
  'SlowDown',
  'ServiceUnavailable',
  'InternalError',
]);

/**
 * Object storage refused a PUT. Browsers leave `statusText` empty over HTTP/2,
 * so the status and the storage's own error code are kept explicitly: without
 * them the failure reached the user as an error with no reason at all.
 */
export class UploadRequestError extends Error {
  readonly code?: string;
  readonly status: number;

  constructor({ code, detail, status }: { code?: string; detail?: string; status: number }) {
    super(
      `Storage rejected the upload (HTTP ${status}${code ? ` ${code}` : ''})${detail ? `: ${detail}` : ''}`,
    );
    this.name = 'UploadRequestError';
    this.code = code;
    this.status = status;
  }

  /** Whether sending the same bytes again can succeed. */
  get retryable(): boolean {
    return (
      this.status === 408 ||
      this.status === 429 ||
      this.status >= 500 ||
      (!!this.code && RETRYABLE_STORAGE_ERROR_CODES.has(this.code))
    );
  }
}

const readStorageError = (xhr: XMLHttpRequest): UploadRequestError => {
  let body = '';
  try {
    body = typeof xhr.responseText === 'string' ? xhr.responseText : '';
  } catch {
    // responseText throws for non-text response types; the status is enough then.
  }
  const code = /<Code>([^<]+)<\/Code>/.exec(body)?.[1]?.trim();
  const detail = /<Message>([^<]+)<\/Message>/.exec(body)?.[1]?.trim() || xhr.statusText || '';

  return new UploadRequestError({ code, detail: detail || undefined, status: xhr.status });
};

const isRetryableUploadError = (error: unknown) =>
  error === UPLOAD_NETWORK_ERROR || (error instanceof UploadRequestError && error.retryable);

const waitBeforeRetry = (ms: number, signal?: AbortSignal) =>
  new Promise<void>((resolve, reject) => {
    if (signal?.aborted) {
      reject(signal.reason ?? new Error('Upload cancelled by user'));
      return;
    }
    const onAbort = () => {
      clearTimeout(timer);
      reject(signal?.reason ?? new Error('Upload cancelled by user'));
    };
    const timer = setTimeout(() => {
      signal?.removeEventListener('abort', onAbort);
      resolve();
    }, ms);
    signal?.addEventListener('abort', onAbort, { once: true });
  });

/**
 * Generate file storage path metadata for S3-compatible storage
 * @param originalFilename - Original filename
 * @param options - Path generation options
 * @returns Path metadata including date, dirname, filename, and pathname
 */
const generateFilePathMetadata = (
  originalFilename: string,
  options: { directory?: string; pathname?: string } = {},
): {
  date: string;
  dirname: string;
  filename: string;
  pathname: string;
} => {
  // Generate unique filename with UUID prefix and original extension
  const extension = originalFilename.split('.').at(-1);
  const filename = `${uuid()}.${extension}`;

  // Generate timestamp-based directory path
  const date = (Date.now() / 1000 / 60 / 60).toFixed(0);
  const dirname = `${options.directory || fileEnv.NEXT_PUBLIC_S3_FILE_PATH}/${date}`;
  const pathname = options.pathname ?? `${dirname}/${filename}`;

  return {
    date,
    dirname,
    filename,
    pathname,
  };
};

interface UploadFileToS3Options {
  abortController?: AbortController;
  directory?: string;
  filename?: string;
  onNotSupported?: () => void;
  onProgress?: (status: FileUploadStatus, state: FileUploadState) => void;
  pathname?: string;
  skipCheckFileType?: boolean;
  /** Pins the scope the upload is reserved in; `undefined` follows the active workspace. */
  workspaceId?: string | null;
}

type LambdaClient = ReturnType<typeof scopedLambdaClient>;

class UploadService {
  releaseUpload = async (pathname: string, workspaceId?: string | null) => {
    try {
      await scopedLambdaClient(workspaceId).upload.abortS3Upload.mutate({ pathname });
    } catch (error) {
      console.error('Failed to clean S3 upload:', error);
    }
  };

  /**
   * uniform upload method for both server and client
   */
  uploadFileToS3 = async (
    file: File,
    { onProgress, directory, pathname, abortController, workspaceId }: UploadFileToS3Options,
  ): Promise<{ data: FileMetadata; success: boolean }> => {
    if (file.size > MAX_UPLOAD_FILE_SIZE) throw new Error(UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE);

    // Server-side upload logic

    // if is server mode, upload to server s3,

    const data = await this.uploadToServerS3(file, {
      abortController,
      directory,
      onProgress,
      pathname,
      workspaceId,
    });
    return { data, success: true };
  };

  uploadBase64ToS3 = async (
    base64Data: string,
    options: UploadFileToS3Options = {},
  ): Promise<UploadBase64ToS3Result> => {
    // Parse base64 data
    const { base64, mimeType, type } = parseDataUri(base64Data);

    if (!base64 || !mimeType || type !== 'base64') {
      throw new Error('Invalid base64 data for image');
    }

    // Convert base64 to Blob
    const byteCharacters = atob(base64);
    const byteArrays = [];

    // Process in chunks to avoid memory issues
    for (let offset = 0; offset < byteCharacters.length; offset += 1024) {
      const slice = byteCharacters.slice(offset, offset + 1024);

      const byteNumbers: number[] = Array.from({ length: slice.length });
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }

    const blob = new Blob(byteArrays, { type: mimeType });

    // Determine file extension
    const fileExtension = mimeType.split('/')[1] || 'png';
    const fileName = `${options.filename || `image_${dayjs().format('YYYY-MM-DD-hh-mm-ss')}`}.${fileExtension}`;

    // Create file object
    const file = new File([blob], fileName, { type: mimeType });

    const hash = await hashFile(file, options.abortController?.signal);

    // Use unified upload method
    const { data: metadata } = await this.uploadFileToS3(file, options);

    return {
      fileType: mimeType,
      hash,
      metadata,
      size: file.size,
    };
  };

  uploadDataToS3 = async (data: object, options: UploadFileToS3Options = {}) => {
    const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
    const file = new File([blob], options.filename || 'data.json', { type: 'application/json' });
    return await this.uploadFileToS3(file, options);
  };

  uploadToServerS3 = async (
    file: File,
    {
      onProgress,
      directory,
      pathname,
      abortController,
      workspaceId,
    }: {
      abortController?: AbortController;
      directory?: string;
      onProgress?: (status: FileUploadStatus, state: FileUploadState) => void;
      pathname?: string;
      workspaceId?: string | null;
    },
  ): Promise<FileMetadata> => {
    const client = scopedLambdaClient(workspaceId);
    const {
      date,
      dirname,
      filename,
      pathname: uploadPathname,
    } = generateFilePathMetadata(file.name, { directory, pathname });
    const result = { date, dirname, filename, path: uploadPathname };
    const startTime = Date.now();

    try {
      if (file.size >= MULTIPART_UPLOAD_THRESHOLD) {
        await this.uploadMultipart(
          client,
          file,
          uploadPathname,
          abortController?.signal,
          (loaded) => {
            onProgress?.('uploading', this.getUploadState(loaded, file.size, startTime));
          },
        );
      } else {
        const preSignUrl = await client.upload.createS3PreSignedUrl.mutate({
          pathname: uploadPathname,
          size: file.size,
        });

        await this.putBlob(
          preSignUrl,
          file,
          abortController?.signal,
          (loaded) => {
            onProgress?.('uploading', this.getUploadState(loaded, file.size, startTime));
          },
          file.type,
        );
      }
    } catch (error) {
      await this.releaseUpload(uploadPathname, workspaceId);
      if (abortController?.signal.aborted) {
        onProgress?.('cancelled', { progress: 0, restTime: 0, speed: 0 });
      }
      throw error;
    }

    onProgress?.('success', {
      progress: 100,
      restTime: 0,
      speed: file.size / Math.max((Date.now() - startTime) / 1000, 0.001),
    });

    return result;
  };

  /**
   * PUT a file to a pre-signed URL someone else minted (the agent-share
   * visitor path: `shareChat.createUploadUrl` reserves the key under the
   * CREATOR's quota and hands back the URL). Single PUT only — callers cap the
   * size below the multipart threshold. Reports progress in the same
   * `FileUploadState` shape as {@link uploadToServerS3}; abort/cleanup of the
   * reservation is the caller's job since only it knows which endpoint to hit.
   */
  uploadToPresignedUrl = async (
    file: File,
    url: string,
    {
      abortController,
      onProgress,
    }: {
      abortController?: AbortController;
      onProgress?: (status: FileUploadStatus, state: FileUploadState) => void;
    } = {},
  ): Promise<void> => {
    const startTime = Date.now();

    try {
      await this.putBlob(
        url,
        file,
        abortController?.signal,
        (loaded) => {
          onProgress?.('uploading', this.getUploadState(loaded, file.size, startTime));
        },
        file.type,
      );
    } catch (error) {
      if (abortController?.signal.aborted) {
        onProgress?.('cancelled', { progress: 0, restTime: 0, speed: 0 });
      }
      throw error;
    }

    onProgress?.('success', {
      progress: 100,
      restTime: 0,
      speed: file.size / Math.max((Date.now() - startTime) / 1000, 0.001),
    });
  };

  private getUploadState = (loaded: number, total: number, startTime: number): FileUploadState => {
    const elapsed = Math.max((Date.now() - startTime) / 1000, 0.001);
    const speed = loaded / elapsed;
    const progress = total > 0 ? Number(((loaded / total) * 100).toFixed(1)) : 0;

    return {
      progress: progress === 100 ? 99.9 : progress,
      restTime: speed > 0 ? (total - loaded) / speed : 0,
      speed,
    };
  };

  private putBlob = async (
    url: string,
    blob: Blob,
    signal: AbortSignal | undefined,
    onProgress: (loaded: number) => void,
    contentType?: string,
  ): Promise<string | undefined> => {
    if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');

    const xhr = new XMLHttpRequest();
    const abort = () => xhr.abort();
    signal?.addEventListener('abort', abort, { once: true });

    try {
      return await new Promise<string | undefined>((resolve, reject) => {
        xhr.upload.addEventListener('progress', (event) => {
          if (event.lengthComputable) onProgress(event.loaded);
        });
        xhr.addEventListener('load', () => {
          if (xhr.status >= 200 && xhr.status < 300) {
            resolve(xhr.getResponseHeader?.('ETag') || undefined);
          } else reject(readStorageError(xhr));
        });
        xhr.addEventListener('error', () => {
          if (xhr.status === 0) reject(UPLOAD_NETWORK_ERROR);
          else reject(readStorageError(xhr));
        });
        xhr.addEventListener('abort', () => reject(new Error('Upload cancelled by user')));
        xhr.open('PUT', url);
        if (contentType) xhr.setRequestHeader('Content-Type', contentType);
        xhr.send(blob);
      });
    } finally {
      signal?.removeEventListener('abort', abort);
    }
  };

  /**
   * Send one multipart part, retrying a transient storage or network failure
   * with a freshly signed URL so a single dropped part does not fail a large file.
   */
  private uploadPart = async ({
    client,
    blob,
    onProgress,
    partNumber,
    pathname,
    signal,
    uploadId,
  }: {
    blob: Blob;
    client: LambdaClient;
    onProgress: (loaded: number) => void;
    partNumber: number;
    pathname: string;
    signal: AbortSignal | undefined;
    uploadId: string;
  }): Promise<string | undefined> => {
    for (let attempt = 1; ; attempt++) {
      const url = await client.upload.createS3MultipartUploadPartUrl.mutate({
        partNumber,
        pathname,
        uploadId,
      });

      try {
        return await this.putBlob(url, blob, signal, onProgress);
      } catch (error) {
        if (
          signal?.aborted ||
          attempt >= MULTIPART_PART_MAX_ATTEMPTS ||
          !isRetryableUploadError(error)
        ) {
          throw error;
        }

        onProgress(0);
        await waitBeforeRetry(MULTIPART_PART_RETRY_DELAY_MS * attempt, signal);
      }
    }
  };

  private uploadMultipart = async (
    client: LambdaClient,
    file: File,
    pathname: string,
    signal: AbortSignal | undefined,
    onProgress: (loaded: number) => void,
  ): Promise<void> => {
    const parts: Array<{ etag: string; partNumber: number }> = [];
    const upload = await client.upload.createS3MultipartUpload.mutate({
      contentType: file.type || undefined,
      pathname,
      size: file.size,
    });
    const partSize =
      upload.partSize ?? Math.max(MULTIPART_PART_SIZE, Math.ceil(file.size / MAX_MULTIPART_PARTS));
    const partCount = Math.ceil(file.size / partSize);
    const { uploadId } = upload;

    try {
      for (let partNumber = 1; partNumber <= partCount; partNumber++) {
        if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');

        const offset = (partNumber - 1) * partSize;
        const end = Math.min(offset + partSize, file.size);
        const etag = await this.uploadPart({
          blob: file.slice(offset, end),
          client,
          onProgress: (loaded) => onProgress(offset + loaded),
          partNumber,
          pathname,
          signal,
          uploadId,
        });
        if (etag) parts.push({ etag, partNumber });
        onProgress(end);
      }

      if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');
      // Removing the chip while the parts are being merged cancels this request too.
      await client.upload.completeS3MultipartUpload.mutate(
        {
          partCount,
          parts: parts.length === partCount ? parts : undefined,
          pathname,
          uploadId,
        },
        { signal },
      );
    } catch (error) {
      try {
        await client.upload.abortS3MultipartUpload.mutate({ pathname, uploadId });
      } catch (abortError) {
        console.error('Failed to abort S3 multipart upload:', abortError);
      }
      throw error;
    }
  };
}

export const uploadService = new UploadService();