File size: 12,288 Bytes
17df17b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bfa16e
 
 
 
 
 
17df17b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262c3c2
17df17b
 
 
 
 
 
 
 
 
 
 
 
 
 
a2b3337
 
 
 
 
 
 
 
17df17b
 
 
 
 
a2b3337
17df17b
 
 
 
 
 
 
 
 
4bfa16e
 
17df17b
 
 
 
a2b3337
 
 
 
 
 
17df17b
 
 
 
 
 
 
 
 
 
 
 
 
4bfa16e
 
086a293
4bfa16e
 
 
 
 
 
 
 
 
 
 
 
 
 
17df17b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
086a293
17df17b
 
 
 
4bfa16e
 
 
 
 
 
 
 
 
17df17b
 
086a293
17df17b
4bfa16e
17df17b
086a293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17df17b
 
 
 
 
 
 
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
import assert from "node:assert/strict";
import {webcrypto} from "node:crypto";
import {gzipSync} from "node:zlib";

// The real module's message handler, loader, SHA verification and search core
// execute with a controlled Worker-like global and a deterministic transport.
const isSpace = true;
const localOrigin = "https://reader.example";
const proxyOrigin = isSpace ? localOrigin : "https://voiceofml-search.hf.space";
const messages = [], requests = [];
const scope = {location: {origin: localOrigin}, postMessage: value => messages.push(structuredClone(value))};
Object.defineProperty(globalThis, "crypto", {configurable: true, value: webcrypto});
globalThis.self = scope;
let responseMode = "valid", packed, firstRead, firstFetch, releaseFetch, expire;
let streamCancelled = false;
const nativeSetTimeout = globalThis.setTimeout;
globalThis.setTimeout = (fn, delay, ...args) => {
  if (delay === 60000) expire = fn;
  return nativeSetTimeout(fn, delay, ...args);
};
globalThis.fetch = async (url, options) => {
  requests.push({url: String(url), credentials: options.credentials, signal: options.signal});
  if (responseMode === "http") return new Response("unavailable", {status: 503});
  if (responseMode === "null") return new Response(null, {status: 204});
  if (responseMode === "throw") throw new Error("transport failed");
  if (responseMode === "throw-string") throw "transport string failure";
  if (responseMode === "stream-error") return new Response(new ReadableStream({
    pull() { throw new Error("stream read failed"); }
  }));
  if (responseMode === "wrong-bytes") return new Response(packed.subarray(1));
  if (responseMode === "expired-response") {
    const response = new Response(packed);
    // The headers arrived, but the load deadline expired before body reading.
    expire();
    return response;
  }
  if (responseMode === "too-large") {
    const chunk = new Uint8Array(16 * 1024 * 1024);
    return new Response(new ReadableStream({
      pull(controller) { controller.enqueue(chunk); },
      cancel() { streamCancelled = true; }
    }));
  }
  if (responseMode === "shared-fetch") {
    firstFetch();
    return new Promise(resolve => { releaseFetch = () => resolve(new Response(packed.subarray(1))); });
  }
  if (responseMode === "held-fetch") {
    responseMode = "valid";
    firstFetch();
    return new Promise((resolve, reject) => {
      options.signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), {once: true});
    });
  }
  if (responseMode === "held-stream") {
    responseMode = "valid";
    return new Response(new ReadableStream({
      pull() { firstRead(); return new Promise(() => {}); },
      cancel() { streamCancelled = true; throw new Error("injected stream cancel error"); }
    }));
  }
  return new Response(packed);
};
await import("../../../static/reader/search/workers/reader-chapter-search-worker.mjs");
const send = async data => { await scope.onmessage({data}); };
const latest = () => messages.at(-1);
let id = 0;
async function search(query = "needle") { await send({type:"search", id:++id, query}); return latest(); }
async function buildConfiguration(data, chapters = [{index:1, path:"one", title:"First"}]) {
  packed = gzipSync(Buffer.from(JSON.stringify(data)));
  const sha256 = Buffer.from(await crypto.subtle.digest("SHA-256", packed)).toString("hex");
  return {index:{url:`${proxyOrigin}/api/reader-bucket-resource?path=chapters/ebook/epub/${"a".repeat(64)}/${"b".repeat(16)}/epub-search-index.json.gz`, bytes:packed.length, sha256}, chapters};
}
// Legacy manifests may use non-string titles and version-1 filters represented
// as array-like JSON. Neither was rejected by the previous implementation.
const legacyFilter = Object.assign({length:32}, Object.fromEntries(Array.from({length:32}, (_, i) => [i,255])));
const goodIndex = {version:1, kind:"epub-search-index", chapters:[
  {index:1,path:"one",text:"needle ".repeat(120)+"手机",bigramFilter:legacyFilter}
]};
let config = await buildConfiguration(goodIndex, [{index:1,path:"one",title:42}]);
assert.match((await search()).error, /索引无效/);
await send({type:"init", configuration:null});
assert.match((await search()).error, /索引无效/);
const before = messages.length;
await send(null); await send({type:"cancel"});
assert.equal(messages.length, before);
const invalidPagingRequests = requests.length;
for (const page of [{session:null, offset:"bad"}, {session:1, offset:"0"}]) {
  const invalidId = ++id;
  await send({type:"page", id:invalidId, ...page});
  assert.equal(latest().id, invalidId);
  assert.match(latest().error, /索引无效/);
}
assert.equal(requests.length, invalidPagingRequests);
await send({type:"unknown", id:++id});
assert.match(latest().error, /索引无效/);
for (const index of [
  {...config.index, url:"https://evil.example/api/reader-content"},
  {...config.index, bytes:0}, {...config.index, bytes:64*1024*1024+1},
  {...config.index, sha256:"bad"}, {...config.index, text_profile:42},
  {...config.index, url:proxyOrigin+"/api/reader-bucket-resource?path=../bad"}
]) {
  await send({type:"init", configuration:{...config,index}});
  const count = requests.length;
  assert.match((await search()).error, /索引无效/);
  assert.equal(requests.length, count);
}
for (const [mode, expected] of [["http",/HTTP 503/],["null",/索引无效/],
    ["throw",/transport failed/],["throw-string",/transport string failure/],
    ["stream-error",/stream read failed/],["wrong-bytes",/校验失败/],["too-large",/超过大小限制/],
    ["expired-response",/取消或加载超时/]]) {
  responseMode = mode; await send({type:"init", configuration:config});
  assert.match((await search()).error, expected, mode);
}
assert.equal(streamCancelled, true);
responseMode = "valid";
// A response of exactly the expected length must still match the SHA-256.
const actualHash = config.index.sha256;
const otherHash = (actualHash[0] === "0" ? "1" : "0") + actualHash.slice(1);
await send({type:"init", configuration:{...config,index:{...config.index,sha256:otherHash}}});
assert.match((await search()).error, /校验失败/);
// Abort while the response stream is blocked in read(): the Worker must cancel
// the underlying stream and a subsequent fetch must still be possible.
responseMode = "held-stream"; streamCancelled = false;
await send({type:"init", configuration:config});
let reading = new Promise(resolve => { firstRead = resolve; });
const streamId = ++id, streamSearch = send({type:"search", id:streamId, query:"needle"});
await reading; await send({type:"cancel"}); await streamSearch;
assert.equal(streamCancelled, true);
assert.equal(messages.some(value => value.id === streamId), false);
responseMode = "valid";
config = await buildConfiguration({...goodIndex, kind:"invalid"});
await send({type:"init", configuration:config});
assert.match((await search()).error, /索引不完整/);
const bucketPath = "/api/reader-bucket-resource?path=" + encodeURIComponent(
  "chapters/ebook/epub/" + "a".repeat(64) + "/" + "b".repeat(16) + "/epub-search-index.json.gz");
const profile = "dom-text-v1", needleText = "needle ".repeat(10000);
const v2 = await buildConfiguration({version:2, kind:"epub-search-index", text_profile:profile, chapters:[
  {index:1,path:"one",text:needleText + "手机 ".repeat(65),bf:"CP0BAEAAAAAgAgIAEAAAAIRAAAAAAACAIAgAAAABAAA="},
  {index:2,path:"two",text:"桌面电脑",bf:"AAAAYgAAAAACAAQQQAghAAAEAAAAgAAAhACIAAIIAAE="}
]}, [{index:1,path:"one",title:42}, {index:2,path:"two",title:"Desktop"}]);
const rejectedUrl = isSpace ? "https://voiceofml-search.hf.space" + bucketPath : bucketPath;
const acceptedUrl = isSpace ? bucketPath : proxyOrigin + bucketPath;
const requestsBeforeV2 = requests.length;
await send({type:"init", configuration:{...v2,index:{...v2.index,url:rejectedUrl,text_profile:profile}}});
assert.match((await search("手机")).error, /索引无效/);
assert.equal(requests.length, requestsBeforeV2);
await send({type:"init", configuration:{...v2,index:{...v2.index,url:acceptedUrl}}});
assert.match((await search("手机")).error, /文本格式不一致/);
assert.equal(requests.length, requestsBeforeV2 + 1);
config = {...v2,index:{...v2.index,url:acceptedUrl,text_profile:profile}};
await send({type:"init", configuration:config});
assert.match((await search(" ")).error, /1–2048/);
assert.match((await search("x".repeat(2049))).error, /1–2048/);

// Overlapping searches share one in-flight load; if that load fails, only the
// latest request receives the error and a later search is allowed to retry.
responseMode = "shared-fetch";
let sharedStarted = new Promise(resolve => { firstFetch = resolve; });
const requestCount = requests.length;
const oldId = ++id, old = send({type:"search", id:oldId, query:"needle"});
await sharedStarted;
const currentId = ++id, current = send({type:"search", id:currentId, query:"手机"});
assert.equal(requests.length, requestCount + 1);
releaseFetch(); await Promise.all([old, current]);
assert.equal(messages.some(value => value.id === oldId), false);
assert.equal(latest().id, currentId); assert.match(latest().error, /校验失败/);

// Drive the actual 60-second load deadline deterministically, without waiting.
responseMode = "held-fetch";
let timedStart = new Promise(resolve => { firstFetch = resolve; });
const timedId = ++id, timed = send({type:"search", id:timedId, query:"needle"});
await timedStart; assert.equal(typeof expire, "function"); expire(); await timed;
assert.equal(latest().id, timedId); assert.match(latest().error, /取消或加载超时/);

// Cancel while fetch is pending and retry before the aborted promise settles.
responseMode = "held-fetch";
let started = new Promise(resolve => { firstFetch = resolve; });
const abandonedId = ++id, abandoned = send({type:"search", id:abandonedId, query:"needle"});
await started; await send({type:"cancel"});
const resumedId = ++id, resumed = send({type:"search", id:resumedId, query:"needle"});
await Promise.all([abandoned, resumed]);
assert.equal(messages.some(value => value.id === abandonedId), false);
assert.equal(latest().id, resumedId); assert.equal(latest().total, 10000);
assert.equal(latest().results.length, 50);
assert.equal(latest().results[0].location, "第 1 章 · 42");
const loadedRequests = requests.length;
const cached = await search("手机");
assert.equal(cached.total, 65);
assert.equal(cached.offset, 0);
assert.deepEqual(cached.results.map(hit => [hit.chapterIndex,hit.start,hit.length]),
  Array.from({length:50}, (_,i) => [1, needleText.length+i*3, 2]));
await send({type:"page", id:++id, session:cached.session, offset:50});
assert.equal(latest().offset, 50);
assert.equal(latest().session, cached.session);
assert.deepEqual(latest().results.map(hit => [hit.chapterIndex,hit.start,hit.length]),
  Array.from({length:15}, (_,i) => [1, needleText.length+(50+i)*3, 2]));
assert.equal(requests.length, loadedRequests); // the validated index is cached
await send({type:"search", id:resumedId, query:"needle"});
assert.equal(latest().total, 10000);
assert.equal(requests.at(-1).credentials, isSpace ? "same-origin" : "omit");
assert.equal(requests.at(-1).url, proxyOrigin + bucketPath);
await send({type:"page", id:++id, session:resumedId, offset:100});
assert.equal(latest().offset, 100); assert.equal(latest().results.length, 50);
const exec = RegExp.prototype.exec;
let visits = 0;
RegExp.prototype.exec = function (text) {
  const match = exec.call(this, text);
  if (match && this.source === 'needle') visits++;
  return match;
};
try {
  await send({type:'page', id:++id, session:resumedId, offset:999999});
} finally {
  RegExp.prototype.exec = exec;
}
assert.equal(latest().offset, 9950);
assert.deepEqual(latest().results.map(({start,length}) => [start,length]),
  Array.from({length:50}, (_, i) => [(9950 + i) * 7, 6]));
assert.equal(visits, 272, 'late page starts at existing match checkpoint');
await send({type:"page", id:++id, session:999, offset:0});
assert.match(latest().error, /取消/);
await send({type:"cancel"});
await send({type:"page", id:++id, session:resumedId, offset:0});
assert.match(latest().error, /取消/);
globalThis.setTimeout = nativeSetTimeout;
console.log("chapter Worker: transport, integrity, cancellation, retry and paging passed");