client.ts
15.1 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/** 高德逆地理编码客户端、限速、停止信号与 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 主键)不再兼容;v3 在 result 里增存 formatted_address,
* 旧 v2 结果没有这一字段,沿用会让「标准地址」列静默空白 —— 两者都报错换缓存路径,
* 而不是静默地拿不到新字段或把已付费的坐标重查一遍。
*/
export const CACHE_SCHEMA_VERSION = 3;
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;
/** 接口给出的完整地址(含门牌);旧 v2 缓存没有这个字段 */
formatted_address: 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 {
const raw = typeof value === 'string' ? value.trim()
: typeof value === 'number' ? String(value) : '';
// Number('') === 0:不挡住空白就会把「接口没给距离」伪装成「距离 0 米」,
// 这条候选会在最近道路排序里抢在真有距离的那条前面。
if (raw === '') return '';
const number = Number(raw);
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,
formatted_address: text(source.formatted_address),
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', 'formatted_address', '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();
}
}