baidu-client.ts 5.96 KB
/**
 * 百度逆地理编码客户端(Web 服务 API v3)。
 *
 * 与主 client.ts(高德)并列存在:默认入口 key.ts / desktop-worker.ts 走百度,
 * 高德客户端保留备查 —— 用户只有百度商授,不调高德服务。
 *
 * 坐标口径:数据全是 GCJ-02,百度 API 的 coordtype=gcj02ll 直接接受 GCJ-02,
 * 不需要转 BD-09(见 packages/clean-core/src/geo/coord.ts)。
 *
 * 返回字段映射到与高德侧相同的 ResultFields,下游 fill.ts / 缓存格式一行不改。
 */

import type { LookupClient, ResultFields, RoadCandidate, Clock, Transport } from './client.ts';
import {
  isRecord, text, distanceText, RateLimiter, RequestCancelled,
  QueryError, StopRun, HttpFailure, StopSignal,
} from './client.ts';
import { UserError } from './errors.ts';

export const BAIDU_ENDPOINT = 'https://api.map.baidu.com/reverse_geocoding/v3/';

/** 状态码:百度用 status=0 表示成功;非 0 见 lbsyun 附录 */
const STATUS_OK = 0;
/** 需要停止整个运行的权限/配额类错误 */
const STOP_CODES = new Set([1, 2, 3, 4, 5, 101, 200, 201, 202, 203, 210, 211, 220, 230, 240, 250, 251, 252, 260, 261, 301, 302, 401, 402]);
/** 可重试的服务繁忙/并发超限 */
const RETRY_CODES = new Set([8, 9]);
const RETRYABLE_HTTP = new Set([408, 429, 500, 502, 503, 504]);
const REQUEST_TIMEOUT_SECONDS = 20;
const ATTEMPTS = 4;

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

/** 把百度 result 映射成下游既有契约 */
export function extractBaiduFields(result: unknown): ResultFields {
  const source = isRecord(result) ? result : {};
  const ac = isRecord(source.addressComponent) ? source.addressComponent : {};
  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 c of candidates) {
    if (c.distance === '') continue;
    if (nearest === null || Number(c.distance) < Number(nearest.distance)) nearest = c;
  }
  const streetName = text(ac.street);
  const streetNumber = text(ac.street_number);
  const streetRoad = streetNumber !== '' ? streetNumber : streetName;
  const streetDistance = distanceText(ac.distance);
  return {
    district: text(ac.district),
    township: text(ac.town),
    road: nearest !== null ? nearest.name : streetRoad,
    formatted_address: text(source.formatted_address),
    road_source: nearest !== null ? 'nearest_road' : streetRoad !== '' ? 'street_number' : '',
    road_distance: nearest !== null ? nearest.distance : streetDistance,
    candidates,
    street_road: streetRoad,
    street_distance: streetDistance,
  };
}

const fetchTransport: Transport = async (url, timeoutSeconds) => {
  const response = await fetch(url, {
    headers: { 'User-Agent': 'heatmap-plus-baidu-fill/1.0' },
    signal: AbortSignal.timeout(timeoutSeconds * 1000),
  });
  if (!response.ok) throw new HttpFailure(response.status);
  return { body: await response.text() };
};

export class BaiduClient 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('请设置 BAIDU_KEY 或在提示中输入百度服务端 AK');
    }
    this.key = key.trim();
    // 复用 client.ts 的 StopSignal:可中断退避/限速语义与高德侧完全一致
    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 params = new URLSearchParams({
      ak: this.key,
      output: 'json',
      coordtype: 'gcj02ll',
      extensions_road: 'true',
      location: `${lat},${lng}`, // 百度顺序是 lat,lng —— 与高德相反
    });
    const url = `${BAIDU_ENDPOINT}?${params}`;
    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 status = Number(payload.status);
        if (status === STATUS_OK) {
          const result = payload.result;
          if (!isRecord(result)) throw new InvalidResponse();
          return extractBaiduFields(result);
        }
        if (STOP_CODES.has(status)) throw new StopRun(`百度服务/权限错误:${status}`);
        if (!RETRY_CODES.has(status)) throw new QueryError(`百度请求失败:${status}`);
        error = `百度服务繁忙:${status}`;
      } 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');
  }
}