page-proxy/src/module/proxy/ai-proxy.ts
2025-05-12 23:02:11 +08:00

198 lines
6.3 KiB
TypeScript

import { bucketName, minioClient } from '../minio.ts';
import { IncomingMessage, ServerResponse } from 'http';
import { filterKeys } from './http-proxy.ts';
import { getUserFromRequest } from '@/utils/get-user.ts';
import { UserPermission, Permission } from '@kevisual/permission';
import { getLoginUser } from '@/middleware/auth.ts';
import busboy from 'busboy';
import { getContentType } from '../get-content-type.ts';
import { OssBase } from '@kevisual/oss';
import { parseSearchValue } from '@kevisual/router/browser';
// import { logger } from '@/module/logger.ts';
const getAiProxy = async (req: IncomingMessage, res: ServerResponse, opts: ProxyOptions) => {
const { createNotFoundPage } = opts;
const _u = new URL(req.url, 'http://localhost');
const oss = opts.oss;
const pathname = _u.pathname;
const params = _u.searchParams;
const password = params.get('p');
const hash = params.get('hash');
let objectName = '';
let owner = '';
const { user, app } = getUserFromRequest(req);
if (app === 'ai') {
const version = params.get('version') || '1.0.0'; // root/ai
objectName = pathname.replace(`/${user}/${app}/`, `${user}/${app}/${version}/`);
owner = user;
} else {
objectName = pathname.replace(`/${user}/${app}/`, `${user}/`); // resources/root/
owner = user;
}
try {
const stat = await oss.statObject(objectName);
if (!stat) {
createNotFoundPage('Invalid proxy url');
return true;
}
const permissionInstance = new UserPermission({ permission: stat.metaData as Permission, owner: owner });
const loginUser = await getLoginUser(req);
const checkPermission = permissionInstance.checkPermissionSuccess({
username: loginUser?.tokenUser?.username || '',
password: password,
});
if (!checkPermission.success) {
return createNotFoundPage('no permission');
}
if (hash && stat.etag === hash) {
res.writeHead(304); // not modified
res.end('not modified')
return true;
}
const filterMetaData = filterKeys(stat.metaData, ['size', 'etag', 'last-modified']);
const contentLength = stat.size;
const etag = stat.etag;
const lastModified = stat.lastModified.toISOString();
const fileName = objectName.split('/').pop();
const objectStream = await minioClient.getObject(bucketName, objectName);
const headers = {
'Content-Length': contentLength,
etag,
'last-modified': lastModified,
'x-file-name': fileName,
...filterMetaData,
};
res.writeHead(200, {
...headers,
});
objectStream.pipe(res, { end: true });
return true;
} catch (error) {
console.error(`Proxy request error: ${error.message}`);
createNotFoundPage('Invalid ai proxy url');
return false;
}
};
export const getMetadata = (pathname: string) => {
let meta: any = { 'app-source': 'user-app' };
const isHtml = pathname.endsWith('.html');
if (isHtml) {
meta = {
...meta,
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-cache',
};
} else {
meta = {
...meta,
'content-type': getContentType(pathname),
'cache-control': 'max-age=31536000, immutable',
};
}
return meta;
};
export const postProxy = async (req: IncomingMessage, res: ServerResponse, opts: ProxyOptions) => {
const _u = new URL(req.url, 'http://localhost');
const pathname = _u.pathname;
const oss = opts.oss;
const params = _u.searchParams;
const force = !!params.get('force');
const hash = params.get('hash');
let meta = parseSearchValue(params.get('meta'), { decode: true });
if (!hash && !force) {
return opts?.createNotFoundPage?.('no hash');
}
let objectName = '';
let owner = '';
const { user, app } = getUserFromRequest(req);
if (app === 'ai') {
const version = params.get('version') || '1.0.0'; // root/ai
objectName = pathname.replace(`/${user}/${app}/`, `${user}/${app}/${version}/`);
owner = user;
} else {
objectName = pathname.replace(`/${user}/${app}/`, `${user}/`); // resources/root/
owner = user;
}
const loginUser = await getLoginUser(req);
if (loginUser?.tokenUser?.username !== owner) {
return opts?.createNotFoundPage?.('no permission');
}
const end = (data: any, message?: string, code = 200) => {
res.writeHead(code, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ code: code, data: data, message: message || 'success' }));
};
let statMeta: any = {};
if (!force) {
const check = await oss.checkObjectHash(objectName, hash, meta);
statMeta = check?.metaData || {};
let isNewMeta = false;
if (check.success && JSON.stringify(meta) !== '{}' && !check.equalMeta) {
meta = { ...statMeta, ...getMetadata(pathname), ...meta };
isNewMeta = true;
await oss.replaceObject(objectName, { ...meta });
}
if (check.success) {
return end({ success: true, hash, meta, isNewMeta, equalMeta: check.equalMeta }, '文件已存在');
}
}
const bb = busboy({
headers: req.headers,
limits: {
fileSize: 100 * 1024 * 1024, // 100MB
files: 1,
},
});
let fileProcessed = false;
bb.on('file', async (name, file, info) => {
fileProcessed = true;
try {
// console.log('file', stat?.metaData);
// await sleep(2000);
await oss.putObject(
objectName,
file,
{
...statMeta,
...getMetadata(pathname),
...meta,
},
{ check: false, isStream: true },
);
end({ success: true, name, info, meta: meta?.metaData, statMeta }, '上传成功', 200);
} catch (error) {
end({ error: error }, '上传失败', 500);
}
});
bb.on('finish', () => {
// 只有当没有文件被处理时才执行end
if (!fileProcessed) {
end({ success: false }, '没有接收到文件', 400);
}
});
bb.on('error', (err) => {
console.error('Busboy 错误:', err);
end({ error: err }, '文件解析失败', 500);
});
req.pipe(bb);
};
type ProxyOptions = {
createNotFoundPage: (msg?: string) => any;
oss?: OssBase;
};
export const aiProxy = async (req: IncomingMessage, res: ServerResponse, opts: ProxyOptions) => {
const oss = new OssBase({ bucketName, client: minioClient });
if (!opts.oss) {
opts.oss = oss;
}
if (req.method === 'POST') {
return postProxy(req, res, opts);
}
return getAiProxy(req, res, opts);
};