desktop.ts 12 KB
#!/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, '无法启动界面'));