client.ts 14.6 KB
/** 高德逆地理编码客户端、限速、停止信号与 SQLite 结果缓存。 */
import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import { UserError } from './errors.ts';
import { toMicroDegrees, type Coords } from './coords.ts';

export const ENDPOINT = 'https://restapi.amap.com/v3/geocode/regeo';
export const PARAMETERS: Record<string, string> = {
  extensions: 'all', roadlevel: '0', radius: '1000', output: 'JSON',
};
/**
 * 缓存结构版本。v2 把主键从「Python 版兼容的排序 JSON」换成整数微度,
 * 旧文件(v1 的 request TEXT 主键)不再兼容:结构不认就报错,让用户换一个新的缓存路径,
 * 而不是静默地在旧键空间里查不到、把已付费的坐标重查一遍。
 */
export const CACHE_SCHEMA_VERSION = 2;
const RETRY_CODES = new Set(['10004', '10014', '10015', '10016', '10017',
  '10019', '10020', '10021', '10029']);
const STOP_CODES = new Set(['10001', '10002', '10003', '10005', '10006', '10007', '10008', '10009',
  '10010', '10011', '10012', '10013', '10018', '10026', '10041', '10044', '10045',
  '40000', '40001', '40002', '40003']);
const RETRYABLE_HTTP = new Set([408, 429, 500, 502, 503, 504]);
const REQUEST_TIMEOUT_SECONDS = 20;
const ATTEMPTS = 4;

/** 单个坐标的失败,消息已核验且不含凭证。 */
export class QueryError extends Error {
  name = 'QueryError';
}
/** 账户、权限或配额错误:停止整个运行。 */
export class StopRun extends QueryError {
  name = 'StopRun';
}
/** 运行已在下一次网络请求之前被中断。 */
export class RequestCancelled extends QueryError {
  name = 'RequestCancelled';
}
/** 由传输层抛出的 HTTP 状态错误。 */
export class HttpFailure extends Error {
  name = 'HttpFailure';
  code: number;

  constructor(code: number) {
    super(`HTTP ${code}`);
    this.code = code;
  }
}

class InvalidResponse extends Error {
  name = 'InvalidResponse';
}

export type RoadCandidate = { name: string; distance: string };
export type ResultFields = {
  district: string;
  township: string;
  road: string;
  road_source: string;
  road_distance: string;
  candidates: RoadCandidate[];
  street_road: string;
  street_distance: string;
};
export type Clock = { now(): number; sleep(seconds: number): Promise<void> };
export type Transport = (url: string, timeoutSeconds: number) => Promise<{ body: string }>;
export type StopHandle = { isSet(): boolean; set(): void; wait(seconds: number): Promise<boolean> };
export type LookupClient = {
  requests: number;
  stopEvent: StopHandle;
  lookup(lng: string, lat: string): Promise<ResultFields>;
};

export function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

export function text(value: unknown): string {
  return typeof value === 'string' ? value.trim() : '';
}

/** 接口给的距离是十进制文本;只接受有限非负数,其余留空(距离 0 是有效值) */
export function distanceText(value: unknown): string {
  if (typeof value !== 'string' && typeof value !== 'number') return '';
  const number = Number(String(value).trim());
  return Number.isFinite(number) && number >= 0 ? String(number) : '';
}

/** 选择距离有效且最近的命名道路;门牌道路只作回退。 */
export function extractFields(regeo: unknown): ResultFields {
  const source = isRecord(regeo) ? regeo : {};
  const address = isRecord(source.addressComponent) ? source.addressComponent : {};
  const street = isRecord(address.streetNumber) ? address.streetNumber : {};
  const roads = Array.isArray(source.roads) ? source.roads : [];
  const candidates: RoadCandidate[] = [];
  for (const road of roads) {
    if (!isRecord(road)) continue;
    const name = text(road.name);
    const distance = distanceText(road.distance);
    if (name !== '') candidates.push({ name, distance });
  }
  let nearest: RoadCandidate | null = null;
  for (const candidate of candidates) {
    if (candidate.distance === '') continue;
    if (nearest === null || Number(candidate.distance) < Number(nearest.distance)) nearest = candidate;
  }
  const streetName = text(street.street);
  const streetDistance = distanceText(street.distance);
  return {
    district: text(address.district),
    township: text(address.township),
    road: nearest !== null ? nearest.name : streetName,
    road_source: nearest !== null ? 'nearest_road' : streetName !== '' ? 'street_number' : '',
    road_distance: nearest !== null ? nearest.distance : streetDistance,
    candidates,
    street_road: streetName,
    street_distance: streetDistance,
  };
}

export const systemClock: Clock = {
  now: () => performance.now(),
  sleep: (seconds) => new Promise((resolve) => { setTimeout(resolve, seconds * 1000); }),
};

/** 运行级停止标志;wait 在被停止时立即返回 true,用于可中断的退避与限速。 */
export class StopSignal {
  private readonly clock: Clock;
  private flagged = false;
  private readonly waiters = new Set<(stopped: boolean) => void>();

  constructor(clock: Clock = systemClock) {
    this.clock = clock;
  }

  isSet(): boolean {
    return this.flagged;
  }

  set(): void {
    if (this.flagged) return;
    this.flagged = true;
    const waiters = [...this.waiters];
    this.waiters.clear();
    for (const finish of waiters) finish(true);
  }

  /** 完整等待返回 false;运行先被停止则返回 true。 */
  async wait(seconds: number): Promise<boolean> {
    if (this.flagged) return true;
    return new Promise<boolean>((resolve) => {
      let settled = false;
      const finish = (stopped: boolean) => {
        if (settled) return;
        settled = true;
        this.waiters.delete(finish);
        resolve(stopped);
      };
      this.waiters.add(finish);
      void this.clock.sleep(seconds).then(() => finish(false));
    });
  }
}

/** 所有 worker 与每次重试共享的全局限速;qps 为 0 表示不限。 */
export class RateLimiter {
  private readonly interval: number;
  private readonly clock: Clock;
  private readonly stop: StopSignal;
  private last: number | null = null;

  constructor(qps: number, stop: StopSignal, clock: Clock = systemClock) {
    if (!Number.isFinite(qps) || qps < 0) throw new UserError('qps 必须是有限的非负数');
    this.stop = stop;
    this.clock = clock;
    this.interval = qps ? 1000 / qps : 0;
  }

  async acquire(): Promise<void> {
    if (this.stop.isSet()) throw new RequestCancelled('运行已停止');
    if (this.interval === 0) return;
    const now = this.clock.now();
    const slot = this.last === null ? now : Math.max(now, this.last + this.interval);
    this.last = slot;
    // Windows 定时器精度在 100 QPS 下不够用:按精确间隔预留时段,可中断等待。
    if (slot > now && await this.stop.wait((slot - now) / 1000)) {
      throw new RequestCancelled('运行已停止');
    }
  }
}

/** Node 的 fetch 默认校验证书链与主机名,等价于 Python 复用已验证的 SSLContext。 */
export const fetchTransport: Transport = async (url, timeoutSeconds) => {
  const response = await fetch(url, {
    headers: { 'User-Agent': 'amap-csv-fill/1.0' },
    signal: AbortSignal.timeout(timeoutSeconds * 1000),
  });
  if (!response.ok) throw new HttpFailure(response.status);
  return { body: await response.text() };
};

export class AmapClient implements LookupClient {
  readonly key: string;
  readonly stopEvent: StopSignal;
  requests = 0;
  private readonly limiter: RateLimiter;
  private readonly transport: Transport;

  constructor(key: unknown, qps = 100, options: { transport?: Transport; clock?: Clock } = {}) {
    if (typeof key !== 'string' || key.trim() === '') {
      throw new UserError('请设置 AMAP_KEY 或在提示中输入 Web 服务 Key');
    }
    this.key = key.trim();
    this.stopEvent = new StopSignal(options.clock);
    this.limiter = new RateLimiter(qps, this.stopEvent, options.clock);
    this.transport = options.transport ?? fetchTransport;
  }

  async lookup(lng: string, lat: string): Promise<ResultFields> {
    const url = `${ENDPOINT}?${new URLSearchParams({ ...PARAMETERS, key: this.key, location: `${lng},${lat}` })}`;
    for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
      await this.limiter.acquire();
      this.requests += 1;
      let error = '';
      try {
        const { body } = await this.transport(url, REQUEST_TIMEOUT_SECONDS);
        const payload: unknown = JSON.parse(body);
        if (!isRecord(payload)) throw new InvalidResponse();
        const code = String(payload.infocode ?? '');
        // 只输出已核验的五位数字码,绝不记录原始 info 或请求 URL。
        const safeCode = /^\d{5}$/.test(code) ? code : '未知';
        if (String(payload.status) === '1') {
          const regeo = payload.regeocode;
          if (!isRecord(regeo)) throw new InvalidResponse();
          // Key 只在请求 URL 上,接口不会把它回显在 regeocode 里;
          // 日志与缓存只留 extractFields 的八个字段,不做整包深拷贝。
          return extractFields(regeo);
        }
        if (STOP_CODES.has(code)) throw new StopRun(`高德权限、账户或配额错误:${safeCode}`);
        if (!RETRY_CODES.has(code)) throw new QueryError(`高德请求失败:${safeCode}`);
        error = `高德限流或服务繁忙:${safeCode}`;
      } catch (exc) {
        if (exc instanceof StopRun || exc instanceof QueryError || exc instanceof RequestCancelled) throw exc;
        if (exc instanceof HttpFailure) {
          if (exc.code === 401 || exc.code === 403) throw new StopRun(`HTTP 权限错误:${exc.code}`);
          if (!RETRYABLE_HTTP.has(exc.code)) throw new QueryError(`HTTP 请求失败:${exc.code}`);
          error = `HTTP 暂时失败:${exc.code}`;
        } else if (exc instanceof SyntaxError || exc instanceof InvalidResponse) {
          error = '接口响应不是有效 JSON 或缺少结果对象';
        } else {
          error = '网络连接失败或超时';
        }
      }
      if (attempt === ATTEMPTS - 1) throw new QueryError(`${error};已重试 ${ATTEMPTS - 1} 次`);
      if (await this.stopEvent.wait(2 ** attempt)) throw new RequestCancelled('运行已停止');
    }
    throw new Error('unreachable');
  }
}

/**
 * SQLite 结果缓存;续跑依赖同一个缓存文件。
 * 主键是整数微度,另存 district/township/road 三列:邻近推断要一次读全部点,
 * 只取这五列就不必把整包 JSON 解析上百万遍。
 */
const CACHE_COMMIT_EVERY = 200;

export type CachedPoint = { lng: number; lat: number; district: string; township: string; road: string };

export class Cache {
  readonly file: string;
  private readonly db: DatabaseSync;
  private readonly getRow: StatementSync;
  private readonly putRow: StatementSync;
  /** 缓存里已写入但尚未提交的结果数。 */
  private uncommitted = 0;

  constructor(file: string) {
    this.file = path.resolve(file);
    fs.mkdirSync(path.dirname(this.file), { recursive: true });
    this.db = new DatabaseSync(this.file);
    this.db.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
    const declared = this.db.prepare("SELECT value FROM meta WHERE key='schema'")
      .get() as { value: string } | undefined;
    if (declared === undefined) {
      this.db.exec('CREATE TABLE IF NOT EXISTS results '
        + '(lng INTEGER NOT NULL, lat INTEGER NOT NULL, district TEXT NOT NULL,'
        + ' township TEXT NOT NULL, road TEXT NOT NULL, result TEXT NOT NULL, saved_at TEXT NOT NULL,'
        + ' PRIMARY KEY (lng, lat))');
      this.db.prepare("INSERT INTO meta VALUES ('schema', ?)")
        .run(String(CACHE_SCHEMA_VERSION));
    } else if (declared.value !== String(CACHE_SCHEMA_VERSION)) {
      this.db.close();
      throw new UserError(`缓存文件是 v${declared.value} 结构,本工具需要 v${CACHE_SCHEMA_VERSION}:`
        + '请换一个新的 cache 路径重新查询(旧文件的已查结果无法沿用)');
    }
    // v1 的文件没有 meta 表,上面那条 CREATE 不会动它已存在的 results,
    // 所以还要按列名确认一次结构;否则报错会是一句看不懂的 "no such column"
    const columns = new Set((this.db.prepare('PRAGMA table_info(results)').all() as unknown as Array<
      { name: string }>).map((c) => c.name));
    if (!['lng', 'lat', 'district', 'township', 'road', 'result', 'saved_at']
      .every((name) => columns.has(name))) {
      this.db.close();
      throw new UserError('缓存文件的 results 表不是 v2 结构,请换一个新的 cache 路径重新查询');
    }
    this.getRow = this.db.prepare('SELECT district, township, road, result FROM results '
      + 'WHERE lng=? AND lat=?');
    this.putRow = this.db.prepare('INSERT OR REPLACE INTO results VALUES (?,?,?,?,?,?,?)');
  }

  private commit(): void {
    if (this.uncommitted === 0) return;
    this.db.exec('COMMIT');
    this.uncommitted = 0;
  }

  /** 一次把全部已查点读进内存,只在邻近推断开启时调用。 */
  points(): CachedPoint[] {
    return this.db.prepare('SELECT lng, lat, district, township, road FROM results')
      .all() as unknown as CachedPoint[];
  }

  get(coords: Coords): ResultFields | null {
    const [lng, lat] = coords;
    const row = this.getRow.get(toMicroDegrees(lng), toMicroDegrees(lat)) as
      { district: string; township: string; road: string; result: string } | undefined;
    if (row === undefined) return null;
    let value: unknown;
    try {
      value = JSON.parse(row.result);
    } catch {
      value = null;
    }
    const fields = [
      'district', 'township', 'road', 'road_source',
      'road_distance', 'candidates', 'street_road', 'street_distance',
    ];
    if (!isRecord(value) || !fields.every((field) => field in value)) {
      throw new UserError('缓存格式损坏,请使用新的 cache 路径');
    }
    return value as unknown as ResultFields;
  }

  /**
   * 每 200 条提交一次:逐条提交会让每次写入都付一遍磁盘同步,实测单条 219 毫秒,
   * 几万行按小时计。
   */
  put(coords: Coords, result: ResultFields): void {
    if (this.uncommitted === 0) this.db.exec('BEGIN');
    this.uncommitted += 1;
    this.putRow.run(
      toMicroDegrees(coords[0]), toMicroDegrees(coords[1]),
      result.district, result.township, result.road,
      JSON.stringify(result),
      new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
    );
    if (this.uncommitted >= CACHE_COMMIT_EVERY) this.commit();
  }

  count(): number {
    const row = this.db.prepare('SELECT COUNT(*) AS n FROM results').get() as { n: number };
    return Number(row.n);
  }

  close(): void {
    this.commit();
    this.db.close();
  }
}