engine7 7.1.144 → 7.1.146

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,389 +0,0 @@
1
- // src/travel/oss-pull.ts
2
- import { gunzipSync as gunzipSync2 } from "node:zlib";
3
- import { join as join2 } from "node:path";
4
- import { createHash as createHash3 } from "node:crypto";
5
-
6
- // src/travel/chunk-store.ts
7
- import { createHash, randomUUID } from "node:crypto";
8
- import {
9
- closeSync,
10
- existsSync,
11
- fstatSync,
12
- fsyncSync,
13
- lstatSync,
14
- mkdirSync,
15
- openSync,
16
- readFileSync,
17
- readSync,
18
- renameSync,
19
- unlinkSync,
20
- writeFileSync,
21
- writeSync,
22
- constants
23
- } from "node:fs";
24
- import { gunzipSync, gzipSync } from "node:zlib";
25
- import { dirname, join } from "node:path";
26
- var CHUNK_BYTES = 1024 * 1024;
27
- var SHA = /^[a-f0-9]{64}$/;
28
- var sha256 = (body) => createHash("sha256").update(body).digest("hex");
29
- function validateChunkRef(ref) {
30
- if (!ref || !SHA.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > CHUNK_BYTES)
31
- throw new Error("TRAVEL_INVALID_CHUNK");
32
- }
33
- function validateFileManifest(file) {
34
- if (!file || !SHA.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || !Array.isArray(file.chunks))
35
- throw new Error("TRAVEL_INVALID_FILE");
36
- let total = 0;
37
- for (const ref of file.chunks) {
38
- validateChunkRef(ref);
39
- total += ref.bytes;
40
- }
41
- if (total !== file.bytes) throw new Error("TRAVEL_INVALID_FILE");
42
- }
43
- var ChunkStore = class {
44
- dir;
45
- constructor(dir) {
46
- this.dir = dir;
47
- mkdirSync(dir, { recursive: true, mode: 448 });
48
- }
49
- chunkPath(sha) {
50
- return join(this.dir, sha + ".gz");
51
- }
52
- /** 幂等:同 sha 已存在直接返回;写盘走 tmp+rename,读者永远看不到半个块。 */
53
- async put(body) {
54
- if (!(body instanceof Buffer) || body.length < 1 || body.length > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
55
- const ref = { sha256: sha256(body), bytes: body.length };
56
- const path = this.chunkPath(ref.sha256);
57
- if (!existsSync(path)) {
58
- const temp = path + "." + randomUUID() + ".tmp";
59
- try {
60
- writeFileSync(temp, gzipSync(body), { flag: "wx", mode: 384 });
61
- renameSync(temp, path);
62
- } finally {
63
- try {
64
- if (existsSync(temp)) unlinkSync(temp);
65
- } catch {
66
- }
67
- }
68
- }
69
- return ref;
70
- }
71
- async has(sha) {
72
- if (!SHA.test(sha)) throw new Error("TRAVEL_INVALID_CHUNK");
73
- if (!existsSync(this.chunkPath(sha))) return false;
74
- try {
75
- await this.read(sha);
76
- return true;
77
- } catch {
78
- return false;
79
- }
80
- }
81
- async read(sha, bytes = -1) {
82
- if (!SHA.test(sha) || !Number.isSafeInteger(bytes) || bytes < -1 || bytes > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
83
- let plain;
84
- try {
85
- plain = gunzipSync(readFileSync(this.chunkPath(sha)));
86
- } catch {
87
- throw new Error("TRAVEL_CHUNK_CORRUPT");
88
- }
89
- if (sha256(plain) !== sha || bytes >= 0 && plain.length !== bytes) throw new Error("TRAVEL_CHUNK_CORRUPT");
90
- return plain;
91
- }
92
- /** 读磁盘上的原始 gzip 体(OSS 直传用:线上/磁盘同为 gz,省一次解压重压)。 */
93
- readGzipRaw(sha) {
94
- if (!SHA.test(sha)) throw new Error("TRAVEL_INVALID_CHUNK");
95
- return readFileSync(this.chunkPath(sha));
96
- }
97
- /** 捕获 = 边读边入仓。1122 晚(VACUUM 拆除后 raw 直捕实弹):活引擎的库/wal/
98
- * jsonl 读到一半被写是常态,一律拒绝会把整个准备打死(晓雯 19:31 实弹
99
- * TRAVEL_SOURCE_CHANGED)。策略=重读两轮仍变=活写入者,接受最后一次自洽读
100
- * (sha 与实际读到的字节严格对应;语义撕裂由对端 integrity_check 出声,
101
- * 搬移的权威静止同步随后覆盖)。静止路径(引擎已停)守卫天然不触发。 */
102
- async captureFile(source) {
103
- let lastError = null;
104
- for (let attempt = 0; attempt < 3; attempt++) {
105
- try {
106
- return await this.captureFileOnce(source, attempt === 2);
107
- } catch (error) {
108
- if (!(error instanceof Error) || error.message !== "TRAVEL_SOURCE_CHANGED") throw error;
109
- lastError = error;
110
- }
111
- }
112
- throw lastError;
113
- }
114
- async captureFileOnce(source, acceptLiveWrite) {
115
- const fd = openSync(source, constants.O_RDONLY);
116
- try {
117
- const before = fstatSync(fd, { bigint: true });
118
- if (!before.isFile()) throw new Error("TRAVEL_NOT_REGULAR_FILE");
119
- const digest = createHash("sha256");
120
- const buffer = Buffer.alloc(Math.min(CHUNK_BYTES, Number(before.size) || 1));
121
- const chunks = [];
122
- let bytes = 0;
123
- for (; ; ) {
124
- const count = readSync(fd, buffer, 0, buffer.length, null);
125
- if (!count) break;
126
- const piece = Buffer.from(buffer.subarray(0, count));
127
- digest.update(piece);
128
- bytes += count;
129
- chunks.push(await this.put(piece));
130
- }
131
- const after = fstatSync(fd, { bigint: true });
132
- const pathInfo = lstatSync(source, { bigint: true });
133
- const changed = ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((key) => after[key] !== before[key] || pathInfo[key] !== before[key]) || BigInt(bytes) !== before.size;
134
- if (changed && !acceptLiveWrite) throw new Error("TRAVEL_SOURCE_CHANGED");
135
- if (changed) console.warn(`[travel] ${source} \u6355\u83B7\u671F\u95F4\u6301\u7EED\u88AB\u5199\uFF08\u6D3B\u5F15\u64CE\uFF09\u2014\u2014\u63A5\u53D7\u77AC\u65F6\u5FEB\u7167\uFF0C\u9759\u6B62\u540C\u6B65\u5C06\u8986\u76D6`);
136
- return { sha256: digest.digest("hex"), bytes, chunks };
137
- } finally {
138
- closeSync(fd);
139
- }
140
- }
141
- async restoreFile(file, destination, mode = 384) {
142
- validateFileManifest(file);
143
- if (existsSync(destination)) throw new Error("TRAVEL_DESTINATION_EXISTS");
144
- mkdirSync(dirname(destination), { recursive: true, mode: 448 });
145
- const temp = destination + "." + randomUUID() + ".incoming";
146
- const digest = createHash("sha256");
147
- const fd = openSync(temp, "wx", mode);
148
- try {
149
- for (const ref of file.chunks) {
150
- const body = await this.read(ref.sha256, ref.bytes);
151
- digest.update(body);
152
- let offset = 0;
153
- while (offset < body.length) offset += writeSync(fd, body, offset, body.length - offset);
154
- }
155
- if (digest.digest("hex") !== file.sha256) throw new Error("TRAVEL_FILE_CORRUPT");
156
- fsyncSync(fd);
157
- renameSync(temp, destination);
158
- } finally {
159
- closeSync(fd);
160
- try {
161
- if (existsSync(temp)) unlinkSync(temp);
162
- } catch {
163
- }
164
- }
165
- }
166
- /** 盘上文件是否与 manifest 一致(apply 的跳过判断)。 */
167
- static fileMatches(destination, manifest) {
168
- try {
169
- const info = lstatSync(destination);
170
- if (!info.isFile() || info.size !== manifest.bytes) return false;
171
- const digest = createHash("sha256");
172
- const fd = openSync(destination, constants.O_RDONLY);
173
- try {
174
- const buffer = Buffer.alloc(Math.min(CHUNK_BYTES, manifest.bytes || 1));
175
- for (; ; ) {
176
- const count = readSync(fd, buffer, 0, buffer.length, null);
177
- if (!count) break;
178
- digest.update(buffer.subarray(0, count));
179
- }
180
- } finally {
181
- closeSync(fd);
182
- }
183
- return digest.digest("hex") === manifest.sha256;
184
- } catch {
185
- return false;
186
- }
187
- }
188
- };
189
- function openChunkStore(dir) {
190
- return new ChunkStore(dir);
191
- }
192
-
193
- // src/travel/oss-transport.ts
194
- import { createHmac, createHash as createHash2 } from "node:crypto";
195
-
196
- // src/travel/oss-broker.ts
197
- var cache = /* @__PURE__ */ new WeakMap();
198
- var cacheKey = (o) => JSON.stringify([o.method, o.key, o.contentMD5 ?? "", o.contentType ?? ""]);
199
- function validateAuthorization(config, value, operations) {
200
- if (!value || !Number.isSafeInteger(value.expiresAt) || value.expiresAt > Date.now() / 1e3 + 960 || !Array.isArray(value.objects) || value.objects.length !== operations.length) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
201
- if (!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(value.bucket) || !/^oss-[a-z0-9-]+(?:-internal)?\.aliyuncs\.com$/.test(value.endpoint) && !/^http:\/\/127\.0\.0\.1:\d+$/.test(value.endpoint)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
202
- if (config.bucket && config.bucket !== value.bucket || config.endpoint && config.endpoint !== value.endpoint) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
203
- let tokenId = config.broker.tokenId;
204
- for (let i = 0; i < operations.length; i++) {
205
- const expected = operations[i], actual = value.objects[i], url = new URL(actual.url);
206
- const local = value.endpoint.startsWith("http://127.0.0.1:");
207
- const host = local ? new URL(value.endpoint).host : `${value.bucket}.${value.endpoint}`;
208
- const root = (local ? "/" + value.bucket : "") + "/chunks/7yi/";
209
- const [owner, transferId, ...key] = url.pathname.slice(root.length).split("/");
210
- if (!url.pathname.startsWith(root) || !owner || !/^[1-9][0-9]{0,18}$/.test(owner) || transferId !== config.broker.transferId || key.join("/") !== expected.key || tokenId && owner !== tokenId) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
211
- tokenId = owner;
212
- if (actual.method !== expected.method || actual.key !== expected.key || url.host !== host || url.protocol !== (local ? "http:" : "https:") || url.username || url.password || url.hash || !actual.headers || Object.keys(actual.headers).some((k) => !["Content-MD5", "Content-Type"].includes(k))) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
213
- if (expected.method === "PUT" && (actual.headers["Content-MD5"] !== expected.contentMD5 || actual.headers["Content-Type"] !== expected.contentType)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
214
- }
215
- config.broker.tokenId = tokenId;
216
- }
217
- async function authorize(config, operations) {
218
- const broker = config.broker;
219
- let result;
220
- try {
221
- const response = await fetch(broker.url, { method: "POST", redirect: "error", headers: { Authorization: "Bearer " + broker.apiKey, "Content-Type": "application/json" }, body: JSON.stringify({ transferId: broker.transferId, internal: config.endpoint.includes("-internal."), objects: operations }), signal: AbortSignal.timeout(2e4) });
222
- if (!response.ok) {
223
- await response.body?.cancel();
224
- throw Error(`TRAVEL_OSS_AUTHORIZATION_HTTP_${response.status}`);
225
- }
226
- result = await response.json();
227
- validateAuthorization(config, result, operations);
228
- } catch (error) {
229
- if (error instanceof Error && /^TRAVEL_OSS_AUTHORIZATION_HTTP_[0-9]{3}$/.test(error.message)) throw error;
230
- throw Error("TRAVEL_OSS_AUTHORIZATION_FAILED");
231
- }
232
- return result;
233
- }
234
- async function prepareOssRequests(config, operations) {
235
- if (!config.broker) return;
236
- let entries = cache.get(config);
237
- if (!entries) {
238
- entries = /* @__PURE__ */ new Map();
239
- cache.set(config, entries);
240
- }
241
- const missing = operations.filter((o) => (entries.get(cacheKey(o))?.expiresAt ?? 0) <= Date.now() / 1e3 + 30);
242
- for (let i = 0; i < missing.length; i += 128) {
243
- const batch = missing.slice(i, i + 128), result = await authorize(config, batch);
244
- for (const [index, object] of result.objects.entries()) entries.set(cacheKey(batch[index]), { object, expiresAt: result.expiresAt });
245
- }
246
- }
247
- async function signedOssRequest(config, operation, refresh = false) {
248
- if (refresh) cache.get(config)?.delete(cacheKey(operation));
249
- for (let attempt = 0; attempt < 2; attempt++) {
250
- await prepareOssRequests(config, [operation]);
251
- const entry = cache.get(config)?.get(cacheKey(operation));
252
- if (entry && entry.expiresAt > Date.now() / 1e3 + 30) return entry.object;
253
- }
254
- throw Error("TRAVEL_OSS_AUTHORIZATION_EXPIRED");
255
- }
256
-
257
- // src/travel/oss-transport.ts
258
- function internalEndpointOf(endpoint) {
259
- if (endpoint.includes("-internal.")) return endpoint;
260
- const at = endpoint.indexOf(".aliyuncs.com");
261
- if (at < 0) return endpoint;
262
- return endpoint.slice(0, at) + "-internal" + endpoint.slice(at);
263
- }
264
- function signedHeaders(config, method, resourcePath, headers) {
265
- const date = (/* @__PURE__ */ new Date()).toUTCString();
266
- const all = { ...headers, Date: date };
267
- const ossHeaders = Object.keys(all).filter((key) => key.toLowerCase().startsWith("x-oss-")).sort((a, b) => a < b ? -1 : a > b ? 1 : 0).map((key) => `${key.toLowerCase()}:${all[key]}
268
- `).join("");
269
- const pick = (name) => {
270
- const key = Object.keys(all).find((k) => k.toLowerCase() === name);
271
- return key ? String(all[key]) : "";
272
- };
273
- const stringToSign = `${method}
274
- ${pick("content-md5")}
275
- ${pick("content-type")}
276
- ${date}
277
- ${ossHeaders}/${config.bucket}${resourcePath}`;
278
- if (!config.accessKeyId || !config.accessKeySecret) throw Error("TRAVEL_OSS_NOT_CONFIGURED");
279
- const signature = createHmac("sha1", config.accessKeySecret).update(stringToSign).digest("base64");
280
- return { ...all, Authorization: `OSS ${config.accessKeyId}:${signature}` };
281
- }
282
- async function ossFetch(config, method, resourcePath, body, headers = {}, okCodes = [200]) {
283
- if (config.broker) {
284
- const operation = { method, key: resourcePath.slice(1), ...method === "PUT" ? { contentMD5: md5Base64(body ?? Buffer.alloc(0)), contentType: "application/octet-stream" } : {} };
285
- for (let attempt = 0; attempt < 2; attempt++) {
286
- const signed2 = await signedOssRequest(config, operation, attempt > 0);
287
- let response2;
288
- try {
289
- response2 = await fetch(signed2.url, { method, headers: signed2.headers, body, redirect: "error", signal: AbortSignal.timeout(Math.max(12e4, Math.round((body?.length ?? 0) / 1048576) * 12e3)) });
290
- } catch {
291
- throw Error("TRAVEL_OSS_TRANSFER_FAILED");
292
- }
293
- if (response2.status === 403 && attempt === 0) {
294
- await response2.body?.cancel();
295
- continue;
296
- }
297
- if (!okCodes.includes(response2.status)) {
298
- await response2.body?.cancel();
299
- throw Error(`TRAVEL_OSS_ERROR (${method} \u2192 ${response2.status})`);
300
- }
301
- return response2;
302
- }
303
- throw Error("TRAVEL_OSS_TRANSFER_FAILED");
304
- }
305
- const signed = signedHeaders(config, method, resourcePath, headers);
306
- const scheme = config.endpoint.startsWith("http://") ? "http://" : "https://";
307
- const host = config.endpoint.replace(/^https?:\/\//, "");
308
- const pathStyle = /^[\d.]+$/.test(host) || host.startsWith("localhost") || host.startsWith("127.");
309
- const url = pathStyle ? `${scheme}${host}/${config.bucket}${resourcePath}` : `${scheme}${config.bucket}.${host}${resourcePath}`;
310
- const response = await fetch(url, {
311
- method,
312
- headers: signed,
313
- body,
314
- // 1123 妹妹 review:固定 120s 对慢上行的大块太贴边(10MB@1Mbps≈80s)——
315
- // 按 body 长度放宽(≥120s,每 1MB 加 12s 余量)。
316
- signal: AbortSignal.timeout(Math.max(12e4, Math.round((body?.length ?? 0) / 1024 / 1024) * 12e3))
317
- });
318
- if (!okCodes.includes(response.status)) {
319
- const detail = await response.text().catch(() => "");
320
- throw new Error(`TRAVEL_OSS_ERROR\uFF08${method} ${resourcePath} \u2192 ${response.status}\uFF09\uFF1A${detail.slice(0, 300)}`);
321
- }
322
- return response;
323
- }
324
- var ossChunkKey = (sha) => `/chunks/${sha}.gz`;
325
- async function ossGetChunk(config, sha) {
326
- const response = await ossFetch(config, "GET", ossChunkKey(sha));
327
- return Buffer.from(await response.arrayBuffer());
328
- }
329
- function md5Base64(body) {
330
- return createHash2("md5").update(body).digest("base64");
331
- }
332
-
333
- // src/travel/oss-pull.ts
334
- async function runOssPull(stateDir, concurrency = 16) {
335
- const input = await new Promise((resolve) => {
336
- let all = "";
337
- process.stdin.setEncoding("utf8");
338
- process.stdin.on("data", (chunk) => {
339
- all += chunk;
340
- });
341
- process.stdin.on("end", () => resolve(all));
342
- process.stdin.resume();
343
- });
344
- const request = JSON.parse(input);
345
- return runOssPullRequest(stateDir, request, concurrency);
346
- }
347
- async function runOssPullRequest(stateDir, request, concurrency = 16) {
348
- if (!request?.config?.accessKeyId && !request?.config?.broker || !Array.isArray(request.refs)) throw new Error("TRAVEL_OSS_PULL_INVALID_INPUT");
349
- for (const ref of request.refs) validateChunkRef(ref);
350
- const config = { ...request.config, endpoint: internalEndpointOf(request.config.endpoint) };
351
- if (!config.broker) request.config.accessKeySecret = "";
352
- const deadline = setTimeout(() => {
353
- console.error("[oss-pull] 30 \u5206\u949F\u8D85\u65F6\u672A\u5B8C\u6210\uFF0C\u9000\u51FA");
354
- process.exit(1);
355
- }, 30 * 6e4);
356
- deadline.unref?.();
357
- console.error(`[oss-pull] ${request.refs.length} \u5757 \u2190 ${config.bucket}@${config.endpoint}\uFF08\u5185\u7F51\uFF09`);
358
- const store = openChunkStore(join2(stateDir, ".travel/chunks"));
359
- await prepareOssRequests(config, request.refs.map((ref) => ({ method: "GET", key: `chunks/${ref.sha256}.gz` })));
360
- let pulled = 0, skipped = 0, bytes = 0, done = 0, cursor = 0;
361
- const failures = [];
362
- await Promise.all(Array.from({ length: Math.max(1, Math.min(32, concurrency)) }, async () => {
363
- for (; ; ) {
364
- const index = cursor++;
365
- if (index >= request.refs.length) break;
366
- const ref = request.refs[index];
367
- try {
368
- if (await store.has(ref.sha256)) {
369
- skipped++;
370
- } else {
371
- const plain = gunzipSync2(await ossGetChunk(config, ref.sha256));
372
- if (createHash3("sha256").update(plain).digest("hex") !== ref.sha256) throw new Error("TRAVEL_CHUNK_CORRUPT");
373
- await store.put(plain);
374
- pulled++;
375
- bytes += ref.bytes;
376
- }
377
- } catch {
378
- failures.push(ref);
379
- }
380
- if (++done % 500 === 0) console.error(`[oss-pull] \u8FDB\u5EA6 ${done}/${request.refs.length}`);
381
- }
382
- }));
383
- if (failures.length) throw new Error(`TRAVEL_OSS_PULL_FAILED\uFF08${failures.length}/${request.refs.length} \u5757\u5931\u8D25\uFF09`);
384
- return { pulled, skipped, bytes };
385
- }
386
- export {
387
- runOssPull,
388
- runOssPullRequest
389
- };