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.

21.5 KB
Raw Blame
import { BRANDING_PROVIDER, ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';
import { isLobeHubModelAvailable } from '@lobechat/business-model-bank/model-config';
import { resolveBusinessModelMapping } from '@lobechat/business-model-runtime';
import { ChatErrorType } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { and, eq } from 'drizzle-orm';
import pMap from 'p-map';
import { z } from 'zod';

import { chargeAfterGenerate } from '@/business/server/image-generation/chargeAfterGenerate';
import { chargeBeforeGenerate } from '@/business/server/image-generation/chargeBeforeGenerate';
import { checkFileStorageUsage } from '@/business/server/trpc-middlewares/lambda';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { AsyncTaskModel } from '@/database/models/asyncTask';
import { GenerationTopicModel } from '@/database/models/generationTopic';
import { UserModel } from '@/database/models/user';
import { AiInfraRepos } from '@/database/repositories/aiInfra';
import { type NewGeneration, type NewGenerationBatch } from '@/database/schemas';
import { asyncTasks, generationBatches, generations } from '@/database/schemas';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { getServerGlobalConfig } from '@/server/globalConfig';
import { createAsyncCaller } from '@/server/routers/async/caller';
import {
  isAsyncCallRejectedBeforeRun,
  keepAliveForAsyncRejection,
} from '@/server/routers/async/rejection';
import { getUserScopedAiProviderRuntimeState } from '@/server/services/aiProviderAccess';
import { FileService } from '@/server/services/file';
import {
  AsyncTaskError,
  AsyncTaskErrorType,
  AsyncTaskStatus,
  AsyncTaskType,
} from '@/types/asyncTask';
import { type ProviderConfig } from '@/types/user/settings';
import { resolveImageModelSelection } from '@/utils/defaultImageModel';
import { normalizeImageGenerationParams } from '@/utils/normalizeImageGenerationParams';
import { generateUniqueSeeds } from '@/utils/number';

import { buildEnabledImageProviderModels } from './defaultModel';
import {
  applyLookupPricingParamDefaults,
  findUnsupportedImageParams,
  validateNoUrlsInConfig,
} from './utils';

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

/** Bounds the task updates and refunds when failing a large batch at once. */
const FAIL_UNSTARTED_CONCURRENCY = 5;

const imageProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
  const { ctx } = opts;
  const wsId = ctx.workspaceId ?? undefined;

  return opts.next({
    ctx: {
      asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId, wsId),
      fileService: new FileService(ctx.serverDB, ctx.userId, wsId),
      generationTopicModel: new GenerationTopicModel(ctx.serverDB, ctx.userId, wsId),
    },
  });
});

// Generated images land in storage through `FileService`, which has no quota
// gate of its own — blocking there would fail after the model call is already
// paid for. Admit at submission instead: refuse to start when storage is
// already full, and let an in-flight generation finish.
const imageCreateProcedure = imageProcedure
  .use(withScopedPermission('file:upload'))
  .use(checkFileStorageUsage);

const createImageInputSchema = z.object({
  generationTopicId: z.string(),
  imageNum: z.number(),
  /**
   * Omit (together with or without `provider`) to let the server pick the user's default image
   * model with the same rule as the image page, see `resolveImageModelSelection`.
   */
  model: z.string().optional(),
  params: z
    .object({
      cfg: z.number().optional(),
      height: z.number().optional(),
      imageUrls: z.array(z.string()).optional(),
      prompt: z.string().refine((prompt) => prompt.trim().length > 0, 'prompt is required'),
      seed: z.number().nullish(),
      steps: z.number().optional(),
      width: z.number().optional(),
    })
    .passthrough(),
  /** Omit to use the first enabled provider serving `model`, or the default image model. */
  provider: z.string().optional(),
});
export type CreateImageServicePayload = z.infer<typeof createImageInputSchema>;

const isErrorBatchResult = (
  result: unknown,
): result is {
  data: {
    batch: NewGenerationBatch;
    generations: NewGeneration[];
  };
  success: true;
} =>
  typeof result === 'object' &&
  result !== null &&
  'data' in result &&
  'success' in result &&
  result.success === true;

export const imageRouter = router({
  createImage: imageCreateProcedure
    .input(createImageInputSchema)
    .mutation(async ({ input, ctx }) => {
      const { userId, serverDB, asyncTaskModel, fileService, generationTopicModel } = ctx;
      const wsId = ctx.workspaceId ?? undefined;
      const { generationTopicId, imageNum } = input;
      let params = input.params;

      log('Starting image creation process, input: %O', input);

      const { aiProvider } = await getServerGlobalConfig();
      const aiInfraRepos = new AiInfraRepos(
        serverDB,
        userId,
        aiProvider as Record<string, ProviderConfig>,
        wsId,
      );

      // Callers such as `lh gen image` may omit the model/provider; fill them in from the user's
      // enabled image models with the image page's default rule instead of a client-side guess.
      let model = input.model;
      let provider = input.provider;
      if (!model || !provider) {
        const runtimeState = await getUserScopedAiProviderRuntimeState(userId, () =>
          aiInfraRepos.getAiProviderRuntimeState(),
        );
        const selection = resolveImageModelSelection(
          buildEnabledImageProviderModels(runtimeState),
          { model, provider },
        );
        if (!selection) {
          const requested = [provider, model].filter(Boolean).join('/');
          throw new TRPCError({
            code: 'BAD_REQUEST',
            message: requested
              ? `No enabled image model matched ${requested}.`
              : 'No enabled image model is available.',
          });
        }
        ({ model, provider } = selection);
        log('Resolved image model selection: %s/%s', provider, model);
      }

      const { resolvedModelId } = await resolveBusinessModelMapping(provider, model);

      // Reject lobehub model ids that are no longer in the model bank so callers get a
      // clear error instead of an opaque downstream failure when the underlying channel
      // can't serve the requested id.
      if (
        provider === BRANDING_PROVIDER &&
        !(await isLobeHubModelAvailable(resolvedModelId, 'image', {
          getUserEmail: async () => (await UserModel.findById(serverDB, userId))?.email,
        }))
      ) {
        throw new TRPCError({
          cause: { data: { modelType: 'image', requestedModel: model } },
          code: 'BAD_REQUEST',
          message: ChatErrorType.LobeHubModelDeprecated,
        });
      }

      // Reject params the model does not declare before anything is queued or charged. The
      // schema comes from the same merged model list the image page and image tool read, so a
      // user-customized model is validated against its own declaration. Models without a
      // declared schema (e.g. custom ids) are passed through unchanged.
      const modelCard = (
        await aiInfraRepos.getAiProviderModelList(provider, { type: 'image' })
      ).find((item) => item.id === model);
      const parametersSchema =
        modelCard && 'parameters' in modelCard ? modelCard.parameters : undefined;
      if (parametersSchema) {
        const unsupportedParams = findUnsupportedImageParams(params, parametersSchema);
        if (unsupportedParams.length > 0) {
          throw new TRPCError({
            code: 'BAD_REQUEST',
            message: `Unsupported parameters for ${model}: ${unsupportedParams.join(', ')}. Supported: ${Object.keys(parametersSchema).join(', ')}`,
          });
        }
      }

      // Old clients and API callers may still send a static size with GIF output. Keep the
      // stored batch and queued request consistent with the runtime's automatic GIF sizing.
      params = normalizeImageGenerationParams(params, resolvedModelId);

      // Normalize reference image addresses, store S3 keys uniformly (avoid storing expiring presigned URLs in database)
      let configForDatabase = { ...params };
      // 1) Process multiple images in imageUrls
      if (Array.isArray(params.imageUrls) && params.imageUrls.length > 0) {
        log('Converting imageUrls to S3 keys for database storage: %O', params.imageUrls);
        try {
          const imageKeysWithNull = await Promise.all(
            params.imageUrls.map(async (url) => {
              const key = await fileService.getKeyFromFullUrl(url);
              if (key) {
                log('Converted URL %s to key %s', url, key);
              } else {
                log('Failed to extract key from URL: %s', url);
              }
              return key;
            }),
          );
          const imageKeys = imageKeysWithNull.filter((key): key is string => key !== null);

          configForDatabase = {
            ...configForDatabase,
            imageUrls: imageKeys,
          };
          log('Successfully converted imageUrls to keys for database: %O', imageKeys);
        } catch (error) {
          console.error('Error converting imageUrls to keys: %O', error);
          console.error('Keeping original imageUrls due to conversion error');
        }
      }
      // 2) Process single image in imageUrl
      if (typeof params.imageUrl === 'string' && params.imageUrl) {
        try {
          const key = await fileService.getKeyFromFullUrl(params.imageUrl);
          if (key) {
            log('Converted single imageUrl to key: %s -> %s', params.imageUrl, key);
            configForDatabase = { ...configForDatabase, imageUrl: key };
          } else {
            log('Failed to extract key from single imageUrl: %s', params.imageUrl);
          }
        } catch (error) {
          console.error('Error converting imageUrl to key: %O', error);
          // Keep original value if conversion fails
        }
      }

      // In development, convert localhost proxy URLs to S3 URLs for async task access
      let generationParams = params;
      if (process.env.NODE_ENV === 'development') {
        const updates: Record<string, unknown> = {};

        // Handle single imageUrl: localhost/f/{id} -> S3 URL
        if (typeof params.imageUrl === 'string' && params.imageUrl) {
          const s3Url = await fileService.getFullFileUrl(configForDatabase.imageUrl as string);
          if (s3Url) {
            log('Dev: converted proxy URL to S3 URL: %s -> %s', params.imageUrl, s3Url);
            updates.imageUrl = s3Url;
          }
        }

        // Handle multiple imageUrls
        if (Array.isArray(params.imageUrls) && params.imageUrls.length > 0) {
          const s3Urls = await Promise.all(
            (configForDatabase.imageUrls as string[]).map((key) => fileService.getFullFileUrl(key)),
          );
          log('Dev: converted proxy URLs to S3 URLs: %O', s3Urls);
          updates.imageUrls = s3Urls;
        }

        if (Object.keys(updates).length > 0) {
          generationParams = { ...params, ...updates };
        }
      }

      // Defensive check: ensure no full URLs enter the database
      validateNoUrlsInConfig(configForDatabase, 'configForDatabase');

      // Backfill lookup-pricing params (e.g. quality/resolution) from model
      // card defaults so omitted optional parameters don't break cost
      // computation before charging. Use the resolved model ID so business
      // aliases without their own model-bank card still resolve pricing.
      generationParams = await applyLookupPricingParamDefaults(
        generationParams,
        resolvedModelId,
        provider,
      );

      const generationTopic = await generationTopicModel.findById(generationTopicId);
      if (!generationTopic) {
        throw new TRPCError({ code: 'FORBIDDEN', message: 'Invalid generation topic' });
      }

      const chargeResult = await chargeBeforeGenerate({
        clientIp: ctx.clientIp,
        configForDatabase,
        generationParams,
        generationTopicId,
        imageNum,
        model,
        provider,
        spendOrigin: ctx.spendOrigin,
        userId,
        workspaceId: wsId,
      });
      // An error batch (insufficient budget / cooldown / frozen workspace) is
      // returned to the client as-is.
      if (isErrorBatchResult(chargeResult)) {
        return chargeResult;
      }
      // Otherwise, opaque per-generation billing handles to thread through each
      // asyncTask so the completion charge can reconcile against them.
      const prechargeItems =
        chargeResult && 'prechargeItems' in chargeResult ? chargeResult.prechargeItems : undefined;

      // Step 1: Atomically create all database records in a transaction
      const { batch: createdBatch, generationsWithTasks } = await serverDB.transaction(
        async (tx) => {
          log('Starting database transaction for image generation');

          // 1. Create generationBatch
          const newBatch: NewGenerationBatch = {
            config: configForDatabase,
            generationTopicId,
            height: params.height,
            model,
            prompt: params.prompt,
            provider,
            userId,
            workspaceId: wsId,
            width: params.width, // Use converted config for database storage
          };
          log('Creating generation batch: %O', newBatch);
          const [batch] = await tx.insert(generationBatches).values(newBatch).returning();
          log('Generation batch created successfully: %s', batch.id);

          // 2. Create generations
          const seeds =
            'seed' in params
              ? generateUniqueSeeds(imageNum)
              : Array.from({ length: imageNum }, () => null);
          const newGenerations: NewGeneration[] = Array.from({ length: imageNum }, (_, index) => {
            return {
              generationBatchId: batch.id,
              seed: seeds[index],
              userId,
              workspaceId: wsId,
            };
          });

          log('Creating %d generations for batch: %s', newGenerations.length, batch.id);
          const createdGenerations = await tx
            .insert(generations)
            .values(newGenerations)
            .returning();
          log(
            'Generations created successfully: %O',
            createdGenerations.map((g) => g.id),
          );

          // 3. Concurrently create asyncTask for each generation (within transaction)
          log('Creating async tasks for generations');
          const generationsWithTasks = await Promise.all(
            createdGenerations.map(async (generation, index) => {
              // Create asyncTask directly in transaction, carrying this
              // generation's billing handle (if any) for the completion charge.
              // Presence check (not truthiness): handles are opaque, so falsy
              // values like 0 or '' must still be stored verbatim.
              const prechargeItem = prechargeItems?.[index];
              // The completion charge runs in the async router, which no longer
              // sees this request; carry the origin attribution on the task so
              // it can still be stamped on the spend log. Stored independently
              // of `precharge` because paths without a billing handle (free /
              // unpriced models) still charge at completion.
              const taskMetadata = {
                ...(prechargeItem === undefined ? {} : { precharge: prechargeItem }),
                ...(ctx.spendOrigin ? { spendOrigin: ctx.spendOrigin } : {}),
              };
              const [createdAsyncTask] = await tx
                .insert(asyncTasks)
                .values({
                  metadata: Object.keys(taskMetadata).length === 0 ? undefined : taskMetadata,
                  status: AsyncTaskStatus.Pending,
                  type: AsyncTaskType.ImageGeneration,
                  userId,
                  workspaceId: wsId,
                })
                .returning();

              const asyncTaskId = createdAsyncTask.id;
              log('Created async task %s for generation %s', asyncTaskId, generation.id);

              // Update generation's asyncTaskId
              await tx
                .update(generations)
                .set({ asyncTaskId })
                .where(and(eq(generations.id, generation.id), eq(generations.userId, userId)));

              return { asyncTaskId, generation };
            }),
          );
          log('All async tasks created in transaction');

          return {
            batch,
            generationsWithTasks,
          };
        },
      );

      log('Database transaction completed successfully. Starting async task triggers directly.');

      // Step 2: Trigger background image generation tasks.
      log('Starting async image generation tasks');

      /**
       * Marks tasks the async router never ran as failed and reconciles their
       * billing: with no async run, its failure handling cannot fire for them.
       */
      const failUnstartedTasks = async (
        tasks: { asyncTaskId: string; index: number }[],
        error: unknown,
      ) => {
        const message =
          'start async task error: ' + (error instanceof Error ? error.message : 'Unknown error');

        await pMap(
          tasks,
          async ({ asyncTaskId }) => {
            try {
              await asyncTaskModel.update(asyncTaskId, {
                error: new AsyncTaskError(AsyncTaskErrorType.ServerError, message),
                status: AsyncTaskStatus.Error,
              });
            } catch (updateError) {
              console.error('Failed to update task status:', updateError);
            }
          },
          { concurrency: FAIL_UNSTARTED_CONCURRENCY },
        );

        if (!ENABLE_BUSINESS_FEATURES || !prechargeItems?.length) return;

        await pMap(
          tasks,
          async ({ asyncTaskId, index }) => {
            const prechargeItem = prechargeItems[index];
            if (prechargeItem === undefined) return;
            try {
              await chargeAfterGenerate({
                isError: true,
                metadata: {
                  ...ctx.spendOrigin,
                  asyncTaskId,
                  generationBatchId: createdBatch.id,
                  modelId: model,
                  topicId: generationTopicId,
                },
                prechargeResult: prechargeItem,
                provider,
                userId,
                workspaceId: wsId,
              });
            } catch (chargeError) {
              console.error('Failed to reconcile billing for failed task:', chargeError);
            }
          },
          { concurrency: FAIL_UNSTARTED_CONCURRENCY },
        );
      };

      try {
        log('Creating unified async caller for userId: %s', userId);

        // Async router will read keyVaults from DB, no need to pass jwtPayload
        const asyncCaller = await createAsyncCaller({
          userId: ctx.userId,
        });

        log('Unified async caller created successfully for userId: %s', ctx.userId);
        log('Processing %d async image generation tasks', generationsWithTasks.length);

        // Fire-and-forget: trigger async tasks without awaiting. The async router
        // handles them independently; the response only waits briefly for a refusal.
        generationsWithTasks.forEach(({ generation, asyncTaskId }, index) => {
          log('Starting background async task %s for generation %s', asyncTaskId, generation.id);

          const call = asyncCaller.image.createImage({
            generationBatchId: createdBatch.id,
            generationId: generation.id,
            generationTopicId,
            model,
            params: generationParams,
            provider,
            taskId: asyncTaskId,
            workspaceId: wsId,
          });
          const handled = call
            // The async router owns the task's status and billing once the request
            // reaches it; a failed HTTP response here (e.g. a proxy timing out a
            // long generation) does not mean the task failed, so only log it.
            // A call its auth middleware refused never ran, so fail that task now
            // instead of leaving it pending until the status poll times it out.
            .catch(async (error: unknown) => {
              console.error('Async image task %s request failed: %O', asyncTaskId, error);
              if (isAsyncCallRejectedBeforeRun(error))
                await failUnstartedTasks([{ asyncTaskId, index }], error);
            });
          keepAliveForAsyncRejection(call, handled);
        });

        log('All %d background async image generation tasks started', generationsWithTasks.length);
      } catch (e) {
        console.error('Failed to process async tasks: %O', e);

        await failUnstartedTasks(
          generationsWithTasks.map(({ asyncTaskId }, index) => ({ asyncTaskId, index })),
          e,
        );
      }

      const createdGenerations = generationsWithTasks.map((item) => ({
        ...item.generation,
        asyncTaskId: item.asyncTaskId,
      }));
      log('Image creation process completed successfully: %O', {
        batchId: createdBatch.id,
        generationCount: createdGenerations.length,
        generationIds: createdGenerations.map((g) => g.id),
      });

      return {
        data: {
          batch: createdBatch,
          generations: createdGenerations,
        },
        success: true,
      };
    }),
});

export type ImageRouter = typeof imageRouter;