🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lobechat/const';
import type { FileUploadItem } from '@lobechat/database/schemas';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { FileS3 } from '@/server/modules/S3';
import { FileUploadService } from '@/server/services/fileUpload';
import {
isMissingObject,
reserveUpload,
uploadConflict,
} from '@/server/services/fileUploadReservation';
const MAX_MULTIPART_PARTS = 10_000;
const MULTIPART_PART_SIZE = 32 * 1024 * 1024;
const multipartUploadSchema = z.object({
pathname: z.string().min(1),
uploadId: z.string().min(1),
});
const multipartPartSchema = z.object({
etag: z.string().min(1),
partNumber: z.number().int().min(1).max(MAX_MULTIPART_PARTS),
});
const uploadSizeSchema = z
.number()
.int()
.min(0)
.max(MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE);
/**
* The content-addressed key the CLI derives for an upload:
* `files/<YYYY-MM-DD>/<sha256>[.<ext>]` (`uploadFileBuffer`).
*/
const CONTENT_ADDRESSED_PATHNAME = /^files\/\d{4}-\d{2}-\d{2}\/[\da-f]{64}(?:\.[\w-]{1,16})?$/;
/**
* A run's operation token reaches this router only to upload acceptance
* evidence or an image its tools returned. It must sign a sized PUT through the reservation, which charges
* quota, bounds the length and refuses a key that already holds an object, and
* only under a content-addressed key, never a pathname of its choosing.
*/
const assertOperationTokenUpload = (
ctx: { heteroOperationScope?: string },
input: { pathname: string; size?: number },
) => {
if (!ctx.heteroOperationScope) return;
if (input.size === undefined || !CONTENT_ADDRESSED_PATHNAME.test(input.pathname)) {
throw new TRPCError({
code: 'FORBIDDEN',
message: "This run's token uploads only sized files under a content-addressed path",
});
}
};
const uploadProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
return opts.next({
ctx: {
fileUploadService: new FileUploadService(
ctx.serverDB,
ctx.userId,
ctx.workspaceId ?? undefined,
),
},
});
});
const getMultipartPartSize = (size: number) =>
Math.max(MULTIPART_PART_SIZE, Math.ceil(size / MAX_MULTIPART_PARTS));
const getActiveSession = async (
service: FileUploadService,
pathname: string,
): Promise<FileUploadItem> => {
const active = await service.touchActive(pathname);
if (active) return active;
if (await service.hasAnyLiveSession(pathname)) {
throw uploadConflict('Upload pathname belongs to another session');
}
throw uploadConflict('Upload session is not active');
};
const validateMultipartSession = (upload: FileUploadItem, input: { uploadId: string }): number => {
if (upload.multipartUploadId !== input.uploadId || !upload.multipartPartSize) {
throw uploadConflict('Multipart upload does not match the active session');
}
return upload.multipartPartSize;
};
const isMissingMultipartUpload = (error: unknown) => {
if (!error || typeof error !== 'object') return false;
const value = error as { $metadata?: { httpStatusCode?: number }; name?: string };
return value.name === 'NoSuchUpload' || value.$metadata?.httpStatusCode === 404;
};
export const uploadRouter = router({
abortS3MultipartUpload: uploadProcedure
.use(withScopedPermission('file:upload'))
.input(multipartUploadSchema)
.mutation(async ({ ctx, input }) => {
const upload = await ctx.fileUploadService.touchActive(input.pathname);
if (!upload) {
if (await ctx.fileUploadService.hasAnyLiveSession(input.pathname)) {
throw uploadConflict('Upload pathname belongs to another session');
}
return { success: true };
}
if (upload.multipartUploadId !== input.uploadId) {
throw uploadConflict('Multipart upload does not match the upload session');
}
await ctx.fileUploadService.release(upload.pathname);
return { success: true };
}),
abortS3Upload: uploadProcedure
.use(withScopedPermission('file:upload'))
.input(z.object({ pathname: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
const upload = await ctx.fileUploadService.findLatest(input.pathname);
if (!upload || upload.status === 'released' || upload.status === 'expired') {
return { success: true };
}
if (upload.status === 'settled') return { success: true };
if (upload.status === 'active') await ctx.fileUploadService.release(input.pathname);
return { success: true };
}),
completeS3MultipartUpload: uploadProcedure
.use(withScopedPermission('file:upload'))
.input(
multipartUploadSchema.extend({
partCount: z.number().int().min(1).max(MAX_MULTIPART_PARTS),
parts: z.array(multipartPartSchema).max(MAX_MULTIPART_PARTS).optional(),
}),
)
.mutation(async ({ ctx, input }) => {
const s3 = new FileS3();
const upload = await getActiveSession(ctx.fileUploadService, input.pathname);
const partSize = validateMultipartSession(upload, input);
const expectedPartCount = Math.ceil(upload.size / partSize);
if (input.partCount !== expectedPartCount) {
throw uploadConflict('Multipart part count does not match the upload session');
}
try {
await s3.completeMultipartUpload(
upload.pathname,
upload.multipartUploadId!,
expectedPartCount,
undefined,
{ partSize, size: upload.size },
);
} catch (error) {
if (!isMissingMultipartUpload(error)) throw error;
const metadata = await s3.getFileMetadata(upload.pathname).catch((headError) => {
if (isMissingObject(headError)) {
throw uploadConflict('Multipart upload no longer exists in storage');
}
throw headError;
});
if (metadata.contentLength !== upload.size) throw error;
}
await ctx.fileUploadService.model.markCompleted(upload.id);
return { success: true };
}),
createS3MultipartUpload: uploadProcedure
.use(withScopedPermission('file:upload'))
.input(
z.object({
contentType: z.string().optional(),
pathname: z.string().min(1),
size: uploadSizeSchema,
}),
)
.mutation(async ({ ctx, input }) => {
const s3 = new FileS3();
const partSize = getMultipartPartSize(input.size);
const upload = await reserveUpload({
clientIp: ctx.clientIp ?? undefined,
db: ctx.serverDB,
model: ctx.fileUploadService.model,
multipartPartSize: partSize,
pathname: input.pathname,
size: input.size,
storage: s3,
userId: ctx.userId,
workspaceId: ctx.workspaceId,
});
if (upload.multipartUploadId) return { partSize, uploadId: upload.multipartUploadId };
let uploadId: string;
try {
uploadId = await s3.createMultipartUpload(upload.pathname, input.contentType);
} catch (error) {
await ctx.fileUploadService.releaseBestEffort(upload.pathname);
throw error;
}
const attached = await ctx.fileUploadService.model.attachMultipartUpload(upload.id, uploadId);
if (attached) return { partSize, uploadId };
await s3.abortMultipartUpload(upload.pathname, uploadId);
const concurrent = await ctx.fileUploadService.model.findActiveByPathname(upload.pathname);
if (concurrent?.multipartUploadId) {
return { partSize: concurrent.multipartPartSize!, uploadId: concurrent.multipartUploadId };
}
throw uploadConflict('Upload session is no longer active');
}),
createS3MultipartUploadPartUrl: uploadProcedure
.use(withScopedPermission('file:upload'))
.input(
multipartUploadSchema.extend({
partNumber: z.number().int().min(1).max(MAX_MULTIPART_PARTS),
}),
)
.mutation(async ({ ctx, input }) => {
const s3 = new FileS3();
const upload = await getActiveSession(ctx.fileUploadService, input.pathname);
const partSize = validateMultipartSession(upload, input);
const partCount = Math.ceil(upload.size / partSize);
if (input.partNumber > partCount) {
throw uploadConflict('Multipart part number does not match the upload session');
}
const contentLength =
input.partNumber === partCount ? upload.size - (partCount - 1) * partSize : partSize;
return s3.createPreSignedUploadPartUrl(
upload.pathname,
upload.multipartUploadId!,
input.partNumber,
contentLength,
);
}),
createS3PreSignedUrl: uploadProcedure
.use(withScopedPermission('file:upload'))
.input(z.object({ pathname: z.string().min(1), size: uploadSizeSchema }))
.mutation(async ({ ctx, input }) => {
assertOperationTokenUpload(ctx, input);
const s3 = new FileS3();
const upload = await reserveUpload({
clientIp: ctx.clientIp ?? undefined,
db: ctx.serverDB,
model: ctx.fileUploadService.model,
pathname: input.pathname,
size: input.size,
storage: s3,
userId: ctx.userId,
workspaceId: ctx.workspaceId,
});
try {
return await s3.createPreSignedUrl(upload.pathname, upload.size);
} catch (error) {
await ctx.fileUploadService.releaseBestEffort(upload.pathname);
throw error;
}
}),
});
export type FileRouter = typeof uploadRouter;