Repository navigation
Expand file tree
/
Copy pathFileFetcherServer.js
More file actions
322 lines (301 loc) · 14.3 KB
/
Copy pathFileFetcherServer.js
File metadata and controls
322 lines (301 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// FileFetcherServer.js
const fs = require('fs').promises;
const { fileURLToPath } = require('url');
const mime = require('mime-types');
const path = require('path');
const crypto = require('crypto');
const failedFetchCache = new Map();
const CACHE_EXPIRATION_MS = 30000; // 30秒内防止重复失败请求
const CACHE_DIR = path.join(__dirname, '.file_cache');
const recentRequests = new Map(); // 用于检测未命中缓存时的快速死循环请求
const REQ_CACHE_EXPIRATION_MS = 5000; // 5秒内重复穿透缓存请求视为潜在循环
const inFlightFetches = new Map(); // Singleflight: 合并同一来源+URL的并发拉取Promise
// 存储对 WebSocketServer 的引用
let webSocketServer = null;
/**
* 初始化 FileFetcherServer,注入依赖。
* @param {object} wss - WebSocketServer 的实例
*/
async function initialize(wss) {
if (!wss || typeof wss.findServerByIp !== 'function' || typeof wss.executeDistributedTool !== 'function') {
throw new Error('FileFetcherServer 初始化失败:传入的 WebSocketServer 实例无效。');
}
webSocketServer = wss;
// 确保缓存目录存在
try {
await fs.mkdir(CACHE_DIR, { recursive: true });
console.log(`[FileFetcherServer] Cache directory ensured at: ${CACHE_DIR}`);
} catch (e) {
console.error(`[FileFetcherServer] Failed to create cache directory: ${e.message}`);
}
console.log('[FileFetcherServer] Initialized and linked with WebSocketServer.');
}
/**
* 归一化请求来源 IP:剥离 ::ffff: 映射前缀并将 ::1 视同 127.0.0.1,
* 避免同一本机双栈回环在缓存/限流键中分裂。
* @param {string|null|undefined} ip
* @returns {string}
*/
function normalizeRequestIp(ip) {
if (typeof ip !== 'string') return '';
const trimmed = ip.trim();
const v4 = trimmed.startsWith('::ffff:') ? trimmed.slice(7) : trimmed;
return v4 === '::1' ? '127.0.0.1' : v4;
}
/**
* 安全提取 VCPChat 内容寻址附件的 SHA-256(64 位十六进制文件名)。
* 先归一化分隔符并切出 basename 再单独解码,即使父目录含未转义 '%' 也不影响附件识别,
* 同时避免抛出 URIError,并兼容无扩展名及大小写十六进制。
* @param {string} fileUrl
* @returns {string|null}
*/
function extractAttachmentSha256(fileUrl) {
if (typeof fileUrl !== 'string') return null;
let rawPath = fileUrl;
try {
rawPath = new URL(fileUrl).pathname;
} catch {
// 无法按标准 URL 解析时沿用原字符串兜底
}
const normalizedSeparators = rawPath
.replace(/\\/g, '/')
.replace(/%(?:2f|5c)/gi, '/');
let baseName = path.posix.basename(normalizedSeparators);
try {
baseName = decodeURIComponent(baseName);
} catch {
// 含未转义 '%'(如 100%_report.png)时原样降级,避免抛出 URIError
}
const match = baseName.match(/^([0-9a-fA-F]{64})(?:\.[A-Za-z0-9_-]+)?$/);
return match ? match[1].toLowerCase() : null;
}
/**
* 计算统一的平台无关本地缓存路径(回归纯粹的 sha256(fileUrl) 寻址)。
* @param {string} fileUrl
* @returns {{ cacheKey: string, originalExtension: string, cachedFilePath: string }}
*/
function getCachedFileInfo(fileUrl) {
const cacheKey = crypto.createHash('sha256').update(fileUrl).digest('hex');
let originalExtension = '';
try {
const pathname = new URL(fileUrl).pathname.replace(/\\/g, '/');
const ext = path.posix.extname(pathname);
if (/^\.[A-Za-z0-9_-]{1,16}$/.test(ext)) {
originalExtension = ext;
}
} catch {
console.warn(`[FileFetcherServer] 无法从URL解析路径名以获取扩展名: ${fileUrl}`);
}
const cachedFilePath = path.join(CACHE_DIR, cacheKey + originalExtension);
return { cacheKey, originalExtension, cachedFilePath };
}
/**
* 原子写入缓存文件(先写同目录唯一 .tmp 再 rename),
* 防止并发 resolveFileUrl 的 fs.access 命中正在写入的半截损坏文件(Torn Read)。
* @param {string} cachedFilePath
* @param {Buffer} buffer
*/
async function writeCacheFileAtomically(cachedFilePath, buffer) {
const tempPath = `${cachedFilePath}.${process.pid}.${Date.now()}-${crypto.randomBytes(4).toString('hex')}.tmp`;
try {
await fs.writeFile(tempPath, buffer);
await fs.rename(tempPath, cachedFilePath);
} catch (err) {
try {
await fs.unlink(tempPath);
} catch {
// ignore cleanup error
}
throw err;
}
}
/**
* 获取文件的 Buffer 和 MIME 类型。
* 如果是本地文件且不存在,则尝试通过 WebSocket 从来源分布式服务器获取。
* @param {string} fileUrl - 文件的 URL (file://...)
* @param {string} requestIp - 发起原始请求的客户端 IP
* @returns {Promise<{buffer: Buffer, mimeType: string}>}
*/
async function fetchFile(fileUrl, requestIp) {
if (typeof fileUrl !== 'string' || !fileUrl.startsWith('file://')) {
throw new Error('FileFetcher 目前只支持 file:// 协议。');
}
const normalizedIpKey = normalizeRequestIp(requestIp) || 'noip';
const requestScopedKey = `${normalizedIpKey}::${fileUrl}`;
const { originalExtension, cachedFilePath } = getCachedFileInfo(fileUrl);
// 1. 优先尝试从本地缓存读取(已落盘缓存直接 O(1) 返回,不受 5s 防循环定时器误伤)
try {
const buffer = await fs.readFile(cachedFilePath);
const mimeType = mime.lookup(cachedFilePath) || 'application/octet-stream';
console.log(`[FileFetcherServer] 成功从本地缓存读取文件: ${cachedFilePath} (原始URL: ${fileUrl})`);
return { buffer, mimeType };
} catch (e) {
if (e.code !== 'ENOENT') {
throw new Error(`读取缓存文件时发生意外错误: ${e.message}`);
}
console.log(`[FileFetcherServer] URL缓存未命中: ${fileUrl}。将尝试从来源服务器获取。`);
}
// 2. Singleflight 并发合并:同一 Turn 多工具并发请求同一未缓存文件时共享同一个拉取 Promise
if (inFlightFetches.has(requestScopedKey)) {
console.log(`[FileFetcherServer] 复用正在进行的并发拉取请求: ${fileUrl} (IP: ${requestIp || 'N/A'})`);
return await inFlightFetches.get(requestScopedKey);
}
// 3. 失败缓存熔断逻辑(30s,按来源 IP + URL 隔离)
const cachedFailure = failedFetchCache.get(requestScopedKey);
if (cachedFailure && (Date.now() - cachedFailure.timestamp < CACHE_EXPIRATION_MS)) {
throw new Error(`文件获取在短时间内已失败,为防止循环已中断。错误: ${cachedFailure.error}`);
}
failedFetchCache.delete(requestScopedKey);
// 4. 快速循环检测(防缓存写盘失败或异常重入时的 5s 内死循环)
const now = Date.now();
if (recentRequests.has(requestScopedKey)) {
const lastRequestTime = recentRequests.get(requestScopedKey);
if (now - lastRequestTime < REQ_CACHE_EXPIRATION_MS) {
recentRequests.set(requestScopedKey, now);
throw new Error(`在 ${REQ_CACHE_EXPIRATION_MS}ms 内检测到对同一文件 '${fileUrl}' 的重复请求。为防止无限循环,已中断操作。`);
}
}
recentRequests.set(requestScopedKey, now);
const recentTimer = setTimeout(() => {
if (recentRequests.get(requestScopedKey) === now) {
recentRequests.delete(requestScopedKey);
}
}, REQ_CACHE_EXPIRATION_MS * 2);
if (typeof recentTimer.unref === 'function') {
recentTimer.unref();
}
if (!requestIp) {
throw new Error('无法确定请求来源,因为缺少 requestIp。');
}
if (!webSocketServer) {
throw new Error('FileFetcherServer 尚未初始化。');
}
const remotePromise = (async () => {
// 1) 单节点直连或单节点隧道:findServerByIp 直接唯一锁定来源节点,任意文件零门槛直通拉取;
// 2) 仅当多台节点共用同一隧道或同一公网 NAT 无法凭 IP 唯一区分时,对 64 位 SHA-256 附件按内容哈希消歧。
const primary = webSocketServer.findServerByIp(requestIp);
let attachHash = null;
let candidates = primary ? [primary] : [];
if (!primary) {
attachHash = extractAttachmentSha256(fileUrl);
if (attachHash) {
const candidateSet = new Set();
if (typeof webSocketServer.findServersByReportedIp === 'function') {
for (const id of webSocketServer.findServersByReportedIp(requestIp)) {
candidateSet.add(id);
}
}
if (typeof webSocketServer.findServersByConnectionIp === 'function') {
for (const id of webSocketServer.findServersByConnectionIp(requestIp)) {
candidateSet.add(id);
}
}
candidates = Array.from(candidateSet);
}
}
if (candidates.length === 0) {
throw new Error(`根据IP [${requestIp}] 未找到任何已知的分布式服务器。`);
}
const errors = [];
for (const serverId of candidates) {
console.log(`[FileFetcherServer] 确定文件来源服务器为: ${serverId} (IP: ${requestIp})。正在请求文件...`);
try {
// 关键:将原始的、未经修改的 fileUrl 作为参数传递给远程工具。
const result = await webSocketServer.executeDistributedTool(serverId, 'internal_request_file', { fileUrl: fileUrl }, 60000);
if (!(result && result.status === 'success' && typeof result.fileData === 'string' && result.fileData.length > 0)) {
throw new Error(result ? result.error : '未知错误');
}
const buffer = Buffer.from(result.fileData, 'base64');
if (attachHash && crypto.createHash('sha256').update(buffer).digest('hex') !== attachHash) {
throw new Error('内容哈希与附件文件名不符');
}
console.log(`[FileFetcherServer] 成功从服务器 ${serverId} 获取到文件 ${fileUrl} 的 Base64 数据。`);
// 原子写入本地缓存,避免并发读取到半截文件
try {
await writeCacheFileAtomically(cachedFilePath, buffer);
console.log(`[FileFetcherServer] 已将获取的文件缓存到本地: ${cachedFilePath}`);
} catch (writeError) {
console.error(`[FileFetcherServer] 无法将获取的文件写入本地缓存: ${writeError.message}`);
}
const mimeType = result.mimeType || mime.lookup(originalExtension) || 'application/octet-stream';
return { buffer, mimeType };
} catch (e) {
errors.push(`${serverId}: ${e.message}`);
}
}
const errorMsg = errors.join(';');
failedFetchCache.set(requestScopedKey, {
timestamp: Date.now(),
error: errorMsg
});
throw new Error(`通过 WebSocket 请求文件失败: ${errorMsg}`);
})();
inFlightFetches.set(requestScopedKey, remotePromise);
try {
return await remotePromise;
} finally {
if (inFlightFetches.get(requestScopedKey) === remotePromise) {
inFlightFetches.delete(requestScopedKey);
}
}
}
/**
* 解析并确保文件存在于本地。
* 如果本地路径存在,直接返回原始 URL。
* 如果不存在,触发 fetchFile 获取缓存,并返回指向缓存的 file:// URL。
* @param {string} fileUrl 文件的 URL (file://...)
* @param {string} requestIp 发起原始请求的客户端 IP
* @returns {Promise<string>} 返回最终的本地可用 file:// URL
*/
async function resolveFileUrl(fileUrl, requestIp) {
if (typeof fileUrl !== 'string' || !fileUrl.startsWith('file://')) {
return fileUrl; // 非 file 协议原样返回
}
// 1. 尝试在主服本机直接解析并访问:
// 若跨操作系统格式不兼容(如 Windows 主服收到 Mac/Linux/Android 节点的 file:///Users/... 抛 ERR_INVALID_FILE_URL_PATH)
// 或本机不存在该文件(ENOENT),均正常进入下方的超栈缓存与跨节点拉取流程,不得提前短路放弃。
let localProbeLabel = fileUrl;
try {
const localPath = fileURLToPath(fileUrl);
localProbeLabel = localPath;
await fs.access(localPath);
return fileUrl; // 本机存在,直接返回给插件读取
} catch {
// 本机不可直接解析或文件不存在,继续走超栈缓存与远程拉取
}
// 2. 先检查本地 .file_cache 是否已有原子落盘的缓存副本
const { cachedFilePath } = getCachedFileInfo(fileUrl);
try {
await fs.access(cachedFilePath);
const cachedUrl = require('url').pathToFileURL(cachedFilePath).href;
console.log(`[FileFetcherServer] File already exists in local cache, bypassing remote fetch: ${cachedUrl}`);
return cachedUrl;
} catch {
console.log(`[FileFetcherServer] ${localProbeLabel} not found locally or in cache, initiating pre-fetch...`);
try {
await fetchFile(fileUrl, requestIp);
const cachedUrl = require('url').pathToFileURL(cachedFilePath).href;
console.log(`[FileFetcherServer] Pre-fetched file wrapped to local cache url: ${cachedUrl}`);
return cachedUrl;
} catch (fetchError) {
console.warn(`[FileFetcherServer] Pre-fetch failed for ${fileUrl}, falling back to original URL: ${fetchError.message}`);
return fileUrl;
}
}
}
module.exports = {
initialize,
fetchFile,
resolveFileUrl,
// Narrow test hooks for deterministic unit & isolation tests; not used by production callers.
__testing: {
normalizeRequestIp,
extractAttachmentSha256,
getCachedFileInfo,
writeCacheFileAtomically,
failedFetchCache,
recentRequests,
inFlightFetches,
CACHE_DIR
}
};