ingest.worker.ts
2.64 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
import { ingestBytes, type IngestProgress } from './ingestCore';
import { ensureLandMask } from '../geo/districtShapes';
import type { DetailColumns, ImportReport, IncidentColumns, MetaFile } from '../aggregate/types';
/**
* 导入解析 Worker。
*
* 为什么要单独一个 Worker(而不是复用聚合 Worker,或干脆留在主线程):
* - 20W 行的 xlsx 解析实测 3.3s、规范化再 ~0.6s。留在主线程等于整个界面
* (地图 WebGL、拖动、弹窗)冻死 4 秒,用户会以为页面挂了;
* - 与聚合 Worker 分开,是因为那个是常驻的、已经持有全量点位,往它身上再压
* 一轮解析会阻塞正在进行的视口聚合;导入是一次性任务,用完即弃最干净;
* - SheetJS 的依赖也只进到这个 chunk,主包不再为它买单。
*
* 产物里的列本来就是 ArrayBuffer,回传时直接 transfer,零拷贝交给主线程落库。
*/
const ctx = self as unknown as DedicatedWorkerGlobalScope;
export type IngestWorkerRequest = { type: 'ingest'; fileName: string; bytes: ArrayBuffer };
export type IngestWorkerResponse =
| { type: 'progress'; phase: 'decode' | 'normalize' | 'clean'; ratio: number }
| { type: 'error'; message: string }
| {
type: 'done';
meta: MetaFile;
columns: IncidentColumns;
detail: DetailColumns;
report: ImportReport;
};
/**
* 解析入口是 async 的:清洗的「坐标落水 / 域外(H 类)」要用陆地掩膜做射线法判定,
* 这里先把陆地掩膜(`geo/shenzhen-land.geojson`)预热一次。模块级缓存,只拉一次,
* 不占解析的时间;拉不到就降级到行政区边界(见 `geo/districtShapes.ts`)。
* `ingestBytes` 内部仍会自行 `ensureLandMask()`,这里提前预热让 fetch 尽早开始。
*/
ctx.onmessage = async (e: MessageEvent<IngestWorkerRequest>) => {
const { fileName, bytes } = e.data;
const post = (msg: IngestWorkerResponse) => ctx.postMessage(msg);
const onProgress: IngestProgress = (phase, ratio) => post({ type: 'progress', phase, ratio });
try {
// 预热陆地掩膜(失败也不致命:降级到行政区边界,海上点只会被少抓,不会误杀)
await ensureLandMask();
const products = await ingestBytes(fileName, bytes, onProgress);
ctx.postMessage(
{
type: 'done',
meta: products.meta,
columns: products.columns,
detail: products.detail,
report: products.report,
} satisfies IngestWorkerResponse,
products.transfer,
);
} catch (err) {
post({ type: 'error', message: err instanceof Error ? err.message : String(err) });
}
};