desktop.ts
12 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
#!/usr/bin/env node
/**
* 图形界面的本机服务:只监听 127.0.0.1,跑的是和命令行完全同一套 runJob —— 界面不另开一套口径。
*
* 为什么用浏览器而不是打包一个桌面程序:工具文件夹要能整包拷给别人、不需要构建、
* 不新增依赖,node:http + 一个静态页面就够。页面拿不到本机绝对路径,所以列目录的活由本机做。
* 一次性 token 拼在网址里,只有这台机器上被打开的这个页面用得着,防止别处的网页往本机发指令。
* Key 只在这一次运行的内存里经过,不写配置、不写日志、不写缓存、不打印。
*/
import crypto from 'node:crypto';
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import process from 'node:process';
import { spawn } from 'node:child_process';
import { Worker } from 'node:worker_threads';
import { reportFailure } from './cli.ts';
import {
CACHE_SUFFIXES, DEFAULT_RADII, LIST_SUFFIXES, ROOT, STATE_FILE, browse, cachePathOf, configState,
formIssue, jobOf, loadState, onlyListNotice, outputNotice, outputOf, quickRoots, saveState,
stageText, summaryOf, tempDirOf,
} from './desktop-core.ts';
import type { UiState } from './desktop-core.ts';
import type { WorkerOut } from './desktop-worker.ts';
import { UserError } from './errors.ts';
import { logPathFor } from './csv-store.ts';
const PAGE = fs.readFileSync(path.join(ROOT, 'desktop.html'), 'utf8');
const TOKEN = crypto.randomBytes(12).toString('hex');
const listeners = new Set<http.ServerResponse>();
let worker: Worker | null = null;
let stopping = false;
function broadcast(event: Record<string, unknown>): void {
const body = `data: ${JSON.stringify(event)}\n\n`;
for (const response of listeners) {
if (response.writable) response.write(body);
}
}
function json(response: http.ServerResponse, code: number, value: unknown): void {
const body = JSON.stringify(value);
response.writeHead(code, {
'content-type': 'application/json; charset=utf-8',
'content-length': Buffer.byteLength(body),
});
response.end(body);
}
function body(req: http.IncomingMessage): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let size = 0;
req.on('data', (chunk: Buffer) => {
size += chunk.length;
// 界面提交的是一张表单,超过这个数只可能是有人在往本地端口灌别的东西
if (size > 64_000) reject(new UserError('请求内容过长'));
else chunks.push(chunk);
});
req.on('end', () => {
try {
const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
reject(new UserError('请求内容格式不对'));
return;
}
resolve(parsed as Record<string, unknown>);
} catch (exc) {
reject(exc instanceof UserError ? exc : new UserError('请求内容格式不对'));
}
});
req.on('error', () => reject(new UserError('请求没有读完')));
});
}
function formOf(given: Record<string, unknown>): UiState {
const base = configState();
const cleaned: Record<string, unknown> = { ...given };
// 表单里的数字是文本;空着的「只处理前几行」表示全量,不是 0
for (const key of ['workers', 'qps', 'streetMeters', 'roadMeters'] as const) {
if (typeof given[key] === 'string') cleaned[key] = Number(given[key]);
}
if (given.limit === '' || given.limit === undefined) cleaned.limit = base.limit;
else if (typeof given.limit === 'string') cleaned.limit = Number(given.limit);
for (const key of ['inferNearby', 'sortIncompleteLast'] as const) {
if (typeof given[key] === 'string') cleaned[key] = given[key] === 'true';
}
return { ...base, ...cleaned } as UiState;
}
function start(given: Record<string, unknown>): string {
if (worker !== null) return '已经有一次运行在进行中';
const state = formOf(given);
const issue = formIssue(state);
if (issue !== '') return issue;
const key = typeof given.key === 'string' ? given.key : '';
saveState(state);
worker = new Worker(new URL('./desktop-worker.ts', import.meta.url), {
workerData: { job: jobOf(state), key },
});
const active = worker;
worker.on('message', (event: WorkerOut) => forward(event));
worker.on('error', (exc) => {
// 线程级崩溃(例如内存不够)走这里:页面上仍是一句人话,完整原文留给终端
const detail = exc instanceof Error ? `${exc.name}: ${exc.message}\n${exc.stack ?? ''}` : String(exc);
process.stderr.write(`运行线程出错:${detail}\n`);
broadcast({ type: 'error', message: '程序内部错误', detail });
});
worker.on('exit', () => {
if (worker === active) worker = null;
stopping = false;
broadcast({ type: 'running', running: false });
});
broadcast({ type: 'running', running: true });
return '';
}
function forward(event: WorkerOut): void {
if (event.type === 'stage') {
const line = stageText(event.label, event.done, event.total);
process.stdout.write(`${line}\n`);
// 一句话只在 desktop-core 写一遍:页面显示的是同一句,不再自己拼一份
broadcast({ ...event, text: line });
} else if (event.type === 'log') {
process.stdout.write(`${event.message}\n`);
broadcast(event);
} else if (event.type === 'done') {
process.stdout.write(`完成:${event.report.rows} 行,接口调用 ${event.report.requests} 次,`
+ `输出 ${event.report.output}\n`);
broadcast({ type: 'done', report: event.report, summary: summaryOf(event.report) });
} else {
if (event.type === 'error') {
process.stderr.write(`无法完成:${event.message}\n`);
if (event.detail !== undefined && event.detail !== '') process.stderr.write(`${event.detail}\n`);
}
broadcast(event);
}
}
/** 缓存文件现有大小:0 表示还没有这个文件。改路径后 /api/check 会重新算一次,提示语不会停在旧值。 */
function cacheSizeOf(state: UiState): number {
try {
return fs.statSync(cachePathOf(state)).size;
} catch {
return 0;
}
}
function bootPayload(): Record<string, unknown> {
const base = configState();
const state = loadState(STATE_FILE, base);
const output = state.input === '' ? '' : outputOf(state);
return {
state,
configDefault: base,
radiiDefault: DEFAULT_RADII,
savedExists: fs.existsSync(STATE_FILE),
quickRoots: quickRoots(),
notice: state.input === '' ? '' : outputNotice(state),
output,
log: output === '' ? '' : logPathFor(output, tempDirOf(state.input)),
cacheSize: cacheSizeOf(state),
running: worker !== null,
};
}
async function handle(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
if (url.searchParams.get('t') !== TOKEN && req.headers['x-token'] !== TOKEN) {
json(res, 403, { error: '这个页面已经失效,请回到终端重新运行一次命令' });
return;
}
if (req.method === 'GET' && url.pathname === '/') {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end(PAGE.replace('%%TOKEN%%', TOKEN));
return;
}
if (req.method === 'GET' && url.pathname === '/api/events') {
res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-store' });
// 先送一行注释:不写这一笔,响应头要等到第一条进度才发出,页面会一直卡在建立连接
res.write(': 已连上\n\n');
listeners.add(res);
req.on('close', () => listeners.delete(res));
return;
}
if (req.method !== 'POST') {
json(res, 404, { error: '没有这个地址' });
return;
}
const given = await body(req);
if (url.pathname === '/api/browse') {
const dir = typeof given.dir === 'string' ? given.dir : '';
const kind = given.kind === 'cache' ? CACHE_SUFFIXES
: given.kind === 'list' ? LIST_SUFFIXES : undefined;
json(res, 200, browse(dir, kind));
return;
}
if (url.pathname === '/api/boot') {
json(res, 200, bootPayload());
return;
}
if (url.pathname === '/api/check') {
const state = formOf(given);
json(res, 200, {
issue: formIssue(state),
notice: outputNotice(state),
cacheSize: cacheSizeOf(state),
listNotice: onlyListNotice(state.onlyList),
});
return;
}
if (url.pathname === '/api/start') {
const issue = start(given);
json(res, issue === '' ? 200 : 400, issue === '' ? { ok: true } : { error: issue });
return;
}
if (url.pathname === '/api/key') {
const value = typeof given.value === 'string' ? given.value : '';
worker?.postMessage({ type: 'key', value });
json(res, 200, { ok: true });
return;
}
if (url.pathname === '/api/stop') {
if (worker === null) {
json(res, 400, { error: '当前没有正在进行的运行' });
return;
}
stopping = true;
worker.postMessage({ type: 'stop' });
process.stdout.write('正在停止:把已经查到的写进表格与缓存,可能需要等一会儿\n');
json(res, 200, { ok: true });
return;
}
if (url.pathname === '/api/open') {
const target = typeof given.path === 'string' ? given.path : '';
json(res, 200, { ok: openIn(target) === '' });
return;
}
json(res, 404, { error: '没有这个地址' });
}
/** 用系统的默认程序打开文件(完成后那三个链接之一)。 */
function openIn(target: string): string {
if (!fs.existsSync(target)) return '文件还不存在';
const command = process.platform === 'win32'
? { file: 'cmd.exe', args: ['/c', 'start', '', target] }
: process.platform === 'darwin' ? { file: 'open', args: [target] }
: { file: 'xdg-open', args: [target] };
try {
const child = spawn(command.file, command.args, { stdio: 'ignore', detached: true });
child.on('error', () => undefined);
child.unref();
return '';
} catch {
return '这台电脑没找到能打开文件的程序';
}
}
function openPage(url: string): void {
// 测试与没有浏览器的电脑上不自动打开;网址照样打印,手动访问即可
if (process.env.AMAP_NO_BROWSER !== undefined) return;
const opened = openIn(url);
if (opened !== '') {
process.stdout.write(`自动打开浏览器没成功(${opened}),请手动访问:\n ${url}\n`);
}
}
async function main(): Promise<number> {
const server = http.createServer((req, res) => {
handle(req, res).catch((exc: unknown) => {
const message = exc instanceof UserError ? exc.message : '界面服务出了点问题';
if (!res.headersSent) json(res, 400, { error: message });
process.stderr.write(`${message}\n`);
});
});
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => resolve());
});
const address = server.address();
const port = typeof address === 'object' && address !== null ? address.port : 0;
const url = `http://127.0.0.1:${port}/?t=${TOKEN}`;
process.stdout.write('补齐工具界面已启动,浏览器里操作;关掉这个窗口或按 Ctrl+C 即停止。\n');
process.stdout.write(` ${url}\n`);
openPage(url);
process.on('SIGINT', () => {
if (worker !== null && !stopping) {
stopping = true;
worker.postMessage({ type: 'stop' });
process.stdout.write('正在停止并写出已完成的部分,再按一次 Ctrl+C 强制退出(缓存已写入的结果仍可复用)\n');
return;
}
worker?.terminate();
server.close();
process.exit(0);
});
await new Promise<void>((resolve) => { server.on('close', () => resolve()); });
return 0;
}
/** 写表那几段可能几分钟不出声,心跳让连接不被当成死了 */
const heartbeat = setInterval(() => {
for (const response of listeners) {
if (response.writable) response.write(': ping\n\n');
}
}, 20_000);
heartbeat.unref();
process.exitCode = await main().catch((exc: unknown) => reportFailure(exc, '无法启动界面'));