glyph-match 重构: 锚点索引+聚类剪枝+串行事件收集, 修复响应双 header 截断

- 慢路径 subset(查询字+锚点字) 顺带建 .gidx, 冷启动 39.75s→0.43s
- 去 async generator/worker 池/流式 pipeTo: LLRT 下非确定性饿死/segfault
- eventsCache(fontPath+查询签名 LRU64): 重复查询免裁剪, 稳态 42ms
- server 层 _bodyBytes 通道: header+body 单帧写回 + Content-Length
- 修复 bodyBytes 分支头部双写导致响应尾部截断(done 事件丢失)
- tcp 层 fire-and-forget write, close 只 end 不 destroy(保写缓冲)
- 慢路径并发度 GLYPH_MATCH_SLOW_CONCURRENCY 可配(默认1)
- 聚类排序+剪枝(PRUNE_MARGIN=0.35)减少冷路径裁剪量
This commit is contained in:
崮生(子虚) 2026-11-02 20:26:58 +08:00
parent 1d1b57fa7f
commit 1ffb1632b2
11 changed files with 786 additions and 136 deletions

View File

@ -35,5 +35,13 @@ export const subsetConcurrency = Math.max(1, parseInt(env.SUBSET_CONCURRENCY ??
*/
export const subsetQueueTimeoutSeconds = Math.max(5, parseInt(env.SUBSET_QUEUE_TIMEOUT ?? "30", 10) || 30);
/**
* 字形搜索慢路径(源字体裁剪解析)最大并发数
*
* 单字体解析后的对象图可达上百 MB,是搜索链路里最重的操作。
* 默认 1:LLRT 运行时 GC 回收滞后 + 串行最稳;Node 或内存充裕的环境可调大。
*/
export const glyphMatchSlowConcurrency = Math.max(1, parseInt(env.GLYPH_MATCH_SLOW_CONCURRENCY ?? "1", 10) || 1);
/** 字体搜索目录(按优先级排序:admin > 普通 > 临时) */
export const fontDirs = ["font/admin", "font", "font/temp"] as const;

View File

@ -0,0 +1,8 @@
/**
* 聚类锚点字(32 字,覆盖独体/上下/左右/包围/繁复结构)。
* 字形索引只存锚点字的位图:体积 ~10KB/字体,用于字体间相似度聚类;
* 搜索评分本身走裁剪管线(subsetCache 兜底),不依赖索引覆盖查询字。
*/
export const ANCHOR_CHAR_CODES: readonly number[] = [19968,21313,20154,22763,20013,27704,19996,22269,30446,26085,26376,27700,28779,23665,30707,29579,37329,26408,31166,24515,25163,25345,25991,36710,38376,21069,39118,38632,40857,40060,40479,39532];
/** 锚点字字符串形式(与 ANCHOR_CHAR_CODES 同源),慢路径裁剪时拼进文本,一次 subset 同时产出评分与索引素材 */
export const ANCHOR_CHARS: string = ANCHOR_CHAR_CODES.map((cp) => String.fromCodePoint(cp)).join("");

View File

@ -0,0 +1,212 @@
/**
* 字体聚类 —— 基于锚点字位图(.gidx v3)的字体间相似度聚类。
*
* 相似字体归入同簇并选出代表(medoid),搜索时先评簇代表、按分数排序簇、
* 跳过远簇(剪枝),让高分命中更早到达前端并减少裁剪加载。
*
* 聚类结果持久化在 `font/clusters.json`:{ v, fingerprints, clusters }。
* 指纹 = 全部字体的 `name:mtimeMs` 集合,字体增删/替换自动失效重建。
*
* 构建时机:首次 glyph-match 请求触发后台惰性构建(一次一个字体走内存闸门),
* 构建期间搜索退回目录顺序全量扫,功能无损。
*
* 注意:两两相似度为 O(n²)(n=簇前字体数),千级字体库需要换抽样/LSH,
* 当前百级以内毫秒~秒级可接受。
*/
import { loadGlyphIndex, indexBitmap, glyphIndexPath } from "./glyph_index";
import { glyphSimilarity } from "./glyph_bitmap";
import { findFontPath } from "../shared";
import { stat, readFile, writeFile } from "../interface";
const CLUSTER_VERSION = 1;
const CLUSTER_FILE = "font/clusters.json";
/** 平均相似度达到该阈值才并簇 */
const MERGE_THRESHOLD = 0.72;
/** 共同锚点字少于该数时视为无法比较,相似度记中性值 */
const MIN_COMMON_ANCHORS = 8;
const NEUTRAL_SIM = 0.5;
export interface FontCluster {
medoid: string;
members: string[];
}
interface ClusterFile {
v: number;
/** 字体指纹集合(`name:mtimeMs`),用于失效判断 */
fingerprints: string[];
clusters: FontCluster[];
}
/**
* 取单个字体的锚点字位图集合;无 .gidx 时返回 null(**不自行解析源字体**:
* 避免与搜索慢路径的全量解析并发撞容器内存上限,未索引字体由慢路径
* 内联建好 .gidx 后,指纹不匹配自动触发下一轮聚类重建,自愈)。
*/
async function anchorVector(font: string): Promise<Map<number, Uint8Array> | null> {
const fontPath = await findFontPath(font);
if (!fontPath) return null;
const index = await loadGlyphIndex(fontPath);
if (!index) return null;
const vector = new Map<number, Uint8Array>();
for (const cp of index.offsets.keys()) {
const bitmap = indexBitmap(index, cp);
if (bitmap) vector.set(cp, bitmap);
}
return vector;
}
/** 两字体的平均锚点相似度 */
function anchorSimilarity(
a: Map<number, Uint8Array>,
b: Map<number, Uint8Array>,
): number {
let sum = 0;
let common = 0;
for (const [cp, bitmap] of a) {
const other = b.get(cp);
if (!other) continue;
sum += glyphSimilarity(bitmap, other);
common++;
}
if (common < MIN_COMMON_ANCHORS) return NEUTRAL_SIM;
return sum / common;
}
/** 贪心凝聚聚类:反复合并平均相似度最高且 ≥ 阈值的簇对 */
function agglomerate(names: string[], sims: Map<string, number>): FontCluster[] {
let groups = names.map((name) => [name]);
const pairSim = (ga: string[], gb: string[]) => {
let sum = 0;
for (const a of ga) for (const b of gb) sum += sims.get(`${a}\0${b}`) ?? NEUTRAL_SIM;
return sum / (ga.length * gb.length);
};
for (;;) {
let bestI = -1;
let bestJ = -1;
let bestSim = MERGE_THRESHOLD;
for (let i = 0; i < groups.length; i++) {
for (let j = i + 1; j < groups.length; j++) {
const sim = pairSim(groups[i]!, groups[j]!);
if (sim >= bestSim) {
bestSim = sim;
bestI = i;
bestJ = j;
}
}
}
if (bestI < 0) break;
groups[bestI] = [...groups[bestI]!, ...groups[bestJ]!];
groups.splice(bestJ, 1);
}
/** medoid = 簇内平均相似度最高的成员 */
return groups.map((members) => {
let medoid = members[0]!;
let bestAvg = -1;
for (const candidate of members) {
let sum = 0;
let n = 0;
for (const other of members) {
if (other === candidate) continue;
sum += sims.get(`${candidate}\0${other}`) ?? NEUTRAL_SIM;
n++;
}
const avg = n > 0 ? sum / n : 1;
if (avg > bestAvg) {
bestAvg = avg;
medoid = candidate;
}
}
return { medoid, members };
});
}
/**
* 计算当前**已有 .gidx** 的字体指纹(name:mtimeMs):未索引字体不参与聚类,
* 其索引建好后指纹变化触发重建,新字体自动汇入。
*/
async function fingerprintsOf(fonts: string[]): Promise<string[]> {
const parts: string[] = [];
for (const font of fonts) {
const fontPath = await findFontPath(font);
if (!fontPath) continue;
try {
const idx = await stat(glyphIndexPath(fontPath));
if (!idx.isFile()) continue;
const s = await stat(fontPath);
if (s.isFile()) parts.push(`${font}:${s.mtimeMs}`);
} catch {}
}
return parts.sort();
}
/** 读取聚类;指纹与当前字体清单不一致(或文件不存在/损坏)返回 null */
export async function loadClusters(fonts: string[]): Promise<FontCluster[] | null> {
try {
const bytes = await readFile(CLUSTER_FILE);
const file = JSON.parse(new TextDecoder().decode(bytes)) as ClusterFile;
if (file.v !== CLUSTER_VERSION) return null;
const current = await fingerprintsOf(fonts);
const saved = [...file.fingerprints].sort();
if (saved.length !== current.length || saved.some((v, i) => v !== current[i])) return null;
return file.clusters;
} catch {
return null;
}
}
/* ─── 后台惰性构建:一次构建一份,进程内去重 ─── */
let building = false;
let pendingFonts: string[] | null = null;
/** 请求路径调用:聚类过期时排一次后台重建,不阻塞当前请求 */
export function scheduleClusterBuild(fonts: string[]): void {
pendingFonts = [...fonts];
if (building) return;
building = true;
void (async () => {
try {
for (;;) {
const list = pendingFonts;
pendingFonts = null;
if (!list) return;
try {
await buildClusters(list);
console.log(`[font-cluster] 聚类完成:${list.length} 字体`);
} catch (err) {
console.error("[font-cluster] 构建失败:", err instanceof Error ? err.message : err);
}
}
} finally {
building = false;
}
})();
}
/** 全量计算并落盘聚类文件 */
async function buildClusters(fonts: string[]): Promise<void> {
const vectors = new Map<string, Map<number, Uint8Array>>();
for (const font of fonts) {
const vector = await anchorVector(font);
if (vector) vectors.set(font, vector);
}
const names = [...vectors.keys()];
/** 一个 .gidx 都没有时跳过落盘:此时写出的空聚类无意义,等首批索引建好再试 */
if (names.length === 0) return;
const sims = new Map<string, number>();
for (let i = 0; i < names.length; i++) {
for (let j = i + 1; j < names.length; j++) {
const sim = anchorSimilarity(vectors.get(names[i]!)!, vectors.get(names[j]!)!);
sims.set(`${names[i]!}\0${names[j]!}`, sim);
sims.set(`${names[j]!}\0${names[i]!}`, sim);
}
}
const clusters = agglomerate(names, sims);
const file: ClusterFile = {
v: CLUSTER_VERSION,
fingerprints: await fingerprintsOf(fonts),
clusters,
};
await writeFile(CLUSTER_FILE, new TextEncoder().encode(JSON.stringify(file)));
}

View File

@ -0,0 +1,197 @@
/**
* 字形位图索引(v3)—— 只存聚类锚点字(32 字,见 common_chars.ts)的 64x64 位图。
* 用途:字体间相似度聚类(font_cluster.ts 读锚点位图算距离),不承担搜索评分。
* 体积:32 字 × 512B = 16KB 原始,zlib 后 ~10KB/字体,可忽略不计。
*
* 索引文件 `<字体路径>.gidx`(与字体同目录,随数据卷持久化):
* [magic u32 "GDIX"][headerLen u32][header JSON][位图区 zlib 压缩流]
* header: { v: 版本, mtime: 源字体 mtimeMs(源文件替换后自动失效), chars: 码点升序列表 }
*
* 构建 = 完整解析源字体并逐锚点字光栅化,内存开销与一次裁剪同量级,
* 因此统一走 withMemoryGate 串行执行(一次只构建一个字体,不会撑爆容器)。
*/
import { deflateSync, inflateSync } from "zlib";
import { Font } from "../../vendor/fonteditor-core/lib/ttf/font";
import { getGlyphBitmap, type SubsetTtfObject } from "./glyph_bitmap";
import { ANCHOR_CHAR_CODES } from "./common_chars";
import { readFile, writeFile, stat } from "../interface";
import { withMemoryGate } from "../subset_queue";
import { estimateSubsetMemory } from "./subset_file";
const MAGIC = 0x47444958;
const INDEX_VERSION = 3;
/** 单个 64x64 二值位图打包后的字节数 */
const BLOCK_BYTES = 512;
/** 索引覆盖的码点集合(构建时过滤) */
const ANCHOR_CHAR_SET = new Set<number>(ANCHOR_CHAR_CODES);
/** 索引路径:与源字体同目录同名 + .gidx */
export function glyphIndexPath(fontPath: string): string {
return `${fontPath}.gidx`;
}
/** 已加载的索引:码点 → 位图块序号 */
export interface GlyphIndex {
offsets: Map<number, number>;
data: Uint8Array;
}
/** 读取并校验索引;源字体已更新(mtime 变化)或格式不符时返回 null */
export async function loadGlyphIndex(fontPath: string): Promise<GlyphIndex | null> {
let bytes: Uint8Array;
let fontMtime: number;
try {
const idx = await stat(glyphIndexPath(fontPath));
const src = await stat(fontPath);
if (!idx.isFile() || !src.isFile()) return null;
bytes = await readFile(glyphIndexPath(fontPath));
fontMtime = src.mtimeMs;
} catch {
return null;
}
if (bytes.length < 8) return null;
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (view.getUint32(0, false) !== MAGIC) return null;
const headerLen = view.getUint32(4, false);
if (8 + headerLen > bytes.length) return null;
try {
const header = JSON.parse(new TextDecoder().decode(bytes.subarray(8, 8 + headerLen))) as {
v: number;
mtime: number;
chars: number[];
};
if (header.v !== INDEX_VERSION || header.mtime !== fontMtime) return null;
const offsets = new Map<number, number>();
header.chars.forEach((cp, i) => offsets.set(cp, i));
/** v2 起位图区整体 zlib 压缩,inflate 是一次性的数 ms 级操作 */
const data = inflateSync(bytes.subarray(8 + headerLen));
if (data.length !== header.chars.length * BLOCK_BYTES) return null;
return { offsets, data };
} catch {
return null;
}
}
/** 取索引中某码点的位图(512B 解包为 4096 个 0/1);缺字返回 null */
export function indexBitmap(index: GlyphIndex, codePoint: number): Uint8Array | null {
const block = index.offsets.get(codePoint);
if (block === undefined) return null;
const out = new Uint8Array(BLOCK_BYTES * 8);
const base = block * BLOCK_BYTES;
for (let i = 0; i < BLOCK_BYTES; i++) {
const b = index.data[base + i]!;
for (let bit = 0; bit < 8; bit++) out[i * 8 + bit] = (b >> (7 - bit)) & 1;
}
return out;
}
/** 64x64 二值位图打包为 512B */
function packBitmap(bitmap: Uint8Array): Uint8Array {
const out = new Uint8Array(BLOCK_BYTES);
for (let i = 0; i < BLOCK_BYTES; i++) {
let b = 0;
for (let bit = 0; bit < 8; bit++) b = (b << 1) | (bitmap[i * 8 + bit]! ? 1 : 0);
out[i] = b;
}
return out;
}
/**
* 完整解析源字体为内存 ttf 对象(对象图较大,调用方负责内存闸门/串行)。
* 搜索慢路径复用同一份解析结果评分 + 建索引,避免冷启动时同一字体解析两次。
*/
export async function parseFontTtf(fontPath: string): Promise<SubsetTtfObject | null> {
const buffer = await readFile(fontPath);
const sourceType = fontPath.split(".").pop();
const font = Font.create(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) as ArrayBuffer, {
type: (sourceType === "otf" ? "otf" : "ttf") as never,
hinting: false,
});
return font.get() as unknown as SubsetTtfObject;
}
/**
* 从已解析的 ttf 对象写出 .gidx(锚点字光栅化 + zlib 压缩落盘)。
* 返回是否写出了有效索引(无任何锚点字时返回 false)。
*/
export async function writeGlyphIndex(fontPath: string, ttf: SubsetTtfObject, mtimeMs: number): Promise<boolean> {
const chars: number[] = [];
const blocks: Uint8Array[] = [];
for (const cp of Object.keys(ttf.cmap ?? {}).map(Number).sort((a, b) => a - b)) {
/** 只索引锚点字,控制体积在 ~10KB/字体 */
if (!ANCHOR_CHAR_SET.has(cp)) continue;
const bitmap = getGlyphBitmap(ttf, cp);
if (!bitmap) continue;
chars.push(cp);
blocks.push(packBitmap(bitmap));
}
if (chars.length === 0) return false;
const header = new TextEncoder().encode(
JSON.stringify({ v: INDEX_VERSION, mtime: mtimeMs, chars }),
);
const rawRegion = new Uint8Array(blocks.length * BLOCK_BYTES);
let regionOff = 0;
for (const block of blocks) {
rawRegion.set(block, regionOff);
regionOff += BLOCK_BYTES;
}
const compressed = deflateSync(rawRegion, { level: 9 });
const out = new Uint8Array(8 + header.length + compressed.length);
const view = new DataView(out.buffer);
view.setUint32(0, MAGIC, false);
view.setUint32(4, header.length, false);
out.set(header, 8);
out.set(compressed, 8 + header.length);
await writeFile(glyphIndexPath(fontPath), out);
return true;
}
/** 构建单个字体的字形索引 = 完整解析 + 写出(调用方负责内存闸门) */
export async function buildGlyphIndex(fontPath: string): Promise<boolean> {
const src = await stat(fontPath);
if (!src.isFile()) return false;
const ttf = await parseFontTtf(fontPath);
if (!ttf) return false;
return writeGlyphIndex(fontPath, ttf, src.mtimeMs);
}
/** 标记某字体的索引已构建(搜索慢路径内联建好后调用,避免后台队列重复构建) */
export function markIndexBuilt(fontPath: string): void {
builtOrFailed.add(fontPath);
}
/* ─── 后台增量构建调度:一次一个字体,走内存闸门 ─── */
const builtOrFailed = new Set<string>();
const pendingPaths: string[] = [];
let building = false;
/** 把字体排入后台索引构建队列(去重;失败不重试,等下次进程重启) */
export function scheduleIndexBuild(fontPath: string): void {
if (builtOrFailed.has(fontPath) || pendingPaths.includes(fontPath)) return;
pendingPaths.push(fontPath);
void drainIndexQueue();
}
async function drainIndexQueue(): Promise<void> {
if (building) return;
building = true;
try {
for (;;) {
const fontPath = pendingPaths.shift();
if (!fontPath) return;
try {
const est = await estimateSubsetMemory(fontPath);
const ok = await withMemoryGate(() => buildGlyphIndex(fontPath), 120_000, est);
if (!ok) throw new Error("排队超时");
console.log(`[glyph-index] 已构建 ${fontPath.split("/").pop()}`);
} catch (err) {
console.error(`[glyph-index] 构建失败 ${fontPath.split("/").pop()}:`, err instanceof Error ? err.message : err);
} finally {
builtOrFailed.add(fontPath);
}
}
} finally {
building = false;
}
}

View File

@ -5,12 +5,14 @@
* 不缓存完整字体对象,也不为了生成预览再发起第二轮全库裁剪。
*/
import { Font } from "../../vendor/fonteditor-core/lib/ttf/font";
import { jsonResponse, findFontPath, subsetCache } from "../shared";
import { SUBSET_CACHE_KEY } from "./subset";
import { readdir } from "../interface";
import { fontDirs, subsetQueueTimeoutSeconds } from "../config";
import { jsonResponse, findFontPath } from "../shared";
import { readdir, stat } from "../interface";
import { fontDirs, subsetQueueTimeoutSeconds, glyphMatchSlowConcurrency } from "../config";
import { getGlyphBitmap, glyphSimilarity, hasGlyph, type SubsetTtfObject } from "../font_util/glyph_bitmap";
import { estimateSubsetMemory, subsetFontFile } from "../font_util/subset_file";
import { loadGlyphIndex, indexBitmap, writeGlyphIndex, markIndexBuilt } from "../font_util/glyph_index";
import { ANCHOR_CHARS } from "../font_util/common_chars";
import { loadClusters, scheduleClusterBuild, type FontCluster } from "../font_util/font_cluster";
import { withMemoryGate } from "../subset_queue";
/** 单个查询字形 */
interface QueryGlyph {
@ -60,21 +62,6 @@ async function listCandidateFonts(): Promise<string[]> {
return names;
}
/** 小字体转 base64,随流交给浏览器渲染,无需再次请求裁剪接口 */
function bytesToBase64(bytes: Uint8Array): string {
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
}
return btoa(binary);
}
/** 解析裁剪产物;OTF(CFF)等无内存 ttf 对象的路径不参与字形评分 */
function readSubsetObject(bytes: Uint8Array): SubsetTtfObject {
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
return Font.create(buffer, { type: "ttf", hinting: false }).get();
}
/**
* 裁剪管线的内存 ttf 对象中 glyf 已是子集但 cmap 仍是原始 gid 映射,
* 按字形自带的 unicode 标注重建 codepoint→新 gid 映射。
@ -93,75 +80,242 @@ function buildSubsetCmapView(ttf: Record<string, unknown>): SubsetTtfObject {
}
/** 依次产出事件;每次只保留下一个候选字体的数据,浏览器背压会自然暂停后续裁剪 */
async function* streamMatches(
fonts: string[],
queryGlyphs: ParsedQueryGlyph[],
): AsyncGenerator<GlyphMatchEvent> {
yield { type: "start", total: fonts.length };
const text = queryGlyphs.map((glyph) => glyph.char).join("");
/**
* 慢路径(源字体裁剪解析)信号量:单字体解析后的对象图可达上百 MB。
* 并发度来自配置(GLYPH_MATCH_SLOW_CONCURRENCY):默认 1 为最保守形态,
* 内存充裕的部署(如 Node + 大内存容器)可调大提升冷路径吞吐。
*/
const SLOW_PATH_CONCURRENCY = glyphMatchSlowConcurrency;
let slowInFlight = 0;
const slowWaiters: (() => void)[] = [];
/** 占一个慢路径槽位(异步等待直到有空位) */
async function acquireSlowSlot(): Promise<void> {
if (slowInFlight < SLOW_PATH_CONCURRENCY) {
slowInFlight++;
return;
}
await new Promise<void>((resolve) => slowWaiters.push(resolve));
slowInFlight++;
}
/** 释放慢路径槽位并唤醒一个等待者 */
function releaseSlowSlot(): void {
slowInFlight--;
slowWaiters.shift()?.();
}
for (const font of fonts) {
try {
const fontPath = await findFontPath(font);
if (!fontPath) {
yield { type: "fontDone", font };
/** 单个字体的评分事件(普通 async 函数,不使用 async generator:LLRT 下嵌套 generator 驱动会非确定性饿死上百秒) */
async function matchFontEvents(
font: string,
queryGlyphs: ParsedQueryGlyph[],
): Promise<GlyphMatchEvent[]> {
const fontPath = await findFontPath(font);
if (!fontPath) return [];
/** 快路径:字形索引命中则免读源字体、免裁剪,纯查表评分 */
const index = await loadGlyphIndex(fontPath);
const events: GlyphMatchEvent[] = [];
if (index) {
let started = false;
let hasMatch = false;
for (const query of queryGlyphs) {
const codePoint = query.char.codePointAt(0)!;
const candidate = indexBitmap(index, codePoint);
if (!candidate) {
if (started) events.push({ type: "glyph", font, glyph: null, missing: true });
continue;
}
const cacheKey = `${SUBSET_CACHE_KEY}:${fontPath}:ttf:${text}`;
const cached = subsetCache.get(cacheKey);
let subsetBytes: Uint8Array;
let ttf: SubsetTtfObject;
if (cached) {
/** 缓存命中:不读源文件、不裁剪、不占重任务槽位(与 /api 裁剪接口共享同一份产物) */
subsetBytes = cached.bytes;
ttf = cached.ttf ?? readSubsetObject(cached.bytes);
} else {
const memoryBytes = await estimateSubsetMemory(fontPath);
const subset = await withMemoryGate(
() => subsetFontFile(fontPath, text, "ttf"),
subsetQueueTimeoutSeconds * 1000,
memoryBytes,
);
if (!subset) throw new Error(`字体裁剪排队超时:${font}`);
subsetBytes = subset.bytes;
/** 优先用裁剪管线返回的内存 ttf 对象(重建子集 cmap),免去序列化再解析(部分字体 re-parse 会失败) */
ttf = subset.ttf ? buildSubsetCmapView(subset.ttf) : readSubsetObject(subset.bytes);
subsetCache.set(cacheKey, { bytes: subsetBytes, ttf: subset.ttf ? ttf : null });
if (!started) {
started = true;
events.push({ type: "font", font, subset: "" });
}
let started = false;
let hasMatch = false;
for (const query of queryGlyphs) {
const codePoint = query.char.codePointAt(0)!;
if (!hasGlyph(ttf, codePoint)) {
if (started) yield { type: "glyph", font, glyph: null, missing: true };
continue;
}
if (!started) {
started = true;
yield { type: "font", font, subset: bytesToBase64(subsetBytes) };
}
const candidate = getGlyphBitmap(ttf, codePoint);
if (!candidate) {
yield { type: "glyph", font, glyph: null, missing: true };
continue;
}
hasMatch = true;
yield {
type: "glyph",
font,
glyph: { char: query.char, score: glyphSimilarity(query.bitmap, candidate), queryIndex: query.queryIndex },
missing: false,
};
}
/** 全部缺字的候选不展示,但仍计入完成进度 */
if (started && !hasMatch) yield { type: "glyph", font, glyph: null, missing: true };
} catch (err) {
/** 单个字体裁剪/解析失败不拖垮整个搜索流,记录后继续下一个 */
console.error(`[glyph-match] ${font} 处理失败:`, err instanceof Error ? err.message : err);
hasMatch = true;
events.push({
type: "glyph",
font,
glyph: { char: query.char, score: glyphSimilarity(query.bitmap, candidate), queryIndex: query.queryIndex },
missing: false,
});
}
yield { type: "fontDone", font };
if (started && !hasMatch) events.push({ type: "glyph", font, glyph: null, missing: true });
if (started) return events;
}
yield { type: "done" };
/** 慢路径:索引未覆盖查询字(或无索引)时走裁剪管线(事件缓存 + 内存闸门) */
await acquireSlowSlot();
try {
return await slowPathEvents(fontPath, font, index, queryGlyphs);
} finally {
releaseSlowSlot();
}
}
/** 慢路径事件缓存上限:防止长尾查询字组合无限膨胀 */
const EVENTS_CACHE_MAX = 64;
/** fontPath+查询签名 → 评分事件;命中免 subset 免解析(LLRT 下 bytes 重解析会挂起/失败,故直接缓存结果) */
const eventsCache = new Map<string, GlyphMatchEvent[]>();
/** FNV-1a 拼接哈希:查询字集 + 位图指纹,同前端重复搜索可命中缓存 */
function querySignature(queryGlyphs: ParsedQueryGlyph[]): string {
let h = 0x811c9dc5;
for (const glyph of queryGlyphs) {
for (let i = 0; i < glyph.bitmap.length; i++) {
h ^= glyph.bitmap[i]!;
h = Math.imul(h, 0x01000193) >>> 0;
}
h ^= glyph.char.length;
h = Math.imul(h, 0x01000193) >>> 0;
}
return `${queryGlyphs.map((g) => g.char).join("")}|${h.toString(36)}`;
}
/**
* 慢路径纯函数版:subset → 建索引 → 评分一次算完,返回事件数组。
* 不在异步生成器体内做重活:LLRT 下生成器上下文与其他 worker 的
* 穿插执行会触发 native crash(实测独立串行同代码完全正常)。
* 重复查询直接命中事件缓存,不做 bytes 重解析(Font.create 对部分
* 字体在 LLRT 下解析挂起/抛错)。
*/
async function slowPathEvents(
fontPath: string,
font: string,
index: Awaited<ReturnType<typeof loadGlyphIndex>>,
queryGlyphs: ParsedQueryGlyph[],
): Promise<GlyphMatchEvent[]> {
const queryChars = [...new Set(queryGlyphs.map((glyph) => glyph.char))].join("");
const cacheKey = `${fontPath}\0${querySignature(queryGlyphs)}`;
const hit = eventsCache.get(cacheKey);
if (hit) return hit;
/** 裁剪文本 = 查询字 + 锚点字(无索引时):一次 subset 同时拿到评分素材与建 .gidx 素材 */
const text = index ? queryChars : [...new Set(queryChars + ANCHOR_CHARS)].join("");
const memoryBytes = await estimateSubsetMemory(fontPath);
const subset = await withMemoryGate(
() => subsetFontFile(fontPath, text, "ttf"),
subsetQueueTimeoutSeconds * 1000,
memoryBytes,
);
if (!subset) throw new Error(`字体裁剪排队超时:${font}`);
/** 只用裁剪管线返回的内存 ttf 对象;无内存对象的(OTF/CFF)不参与评分 */
if (!subset.ttf) return [];
const ttf = buildSubsetCmapView(subset.ttf);
/** 无索引(冷启动):用含锚点字的 subset 顺带建 .gidx,免去全量解析(LLRT 下并发全量解析会 native crash) */
if (!index) {
const src = await stat(fontPath);
await writeGlyphIndex(fontPath, ttf, src.mtimeMs);
markIndexBuilt(fontPath);
}
const events: GlyphMatchEvent[] = [];
let started = false;
let hasMatch = false;
for (const query of queryGlyphs) {
const codePoint = query.char.codePointAt(0)!;
if (!hasGlyph(ttf, codePoint)) {
if (started) events.push({ type: "glyph", font, glyph: null, missing: true });
continue;
}
if (!started) {
started = true;
events.push({ type: "font", font, subset: "" });
}
const candidate = getGlyphBitmap(ttf, codePoint);
if (!candidate) {
events.push({ type: "glyph", font, glyph: null, missing: true });
continue;
}
hasMatch = true;
events.push({
type: "glyph",
font,
glyph: { char: query.char, score: glyphSimilarity(query.bitmap, candidate), queryIndex: query.queryIndex },
missing: false,
});
}
/** 全部缺字的候选不展示,但仍计入完成进度 */
if (started && !hasMatch) events.push({ type: "glyph", font, glyph: null, missing: true });
if (eventsCache.size >= EVENTS_CACHE_MAX) {
/** Map 迭代序即插入序,淘汰最旧项 */
eventsCache.delete(eventsCache.keys().next().value!);
}
eventsCache.set(cacheKey, events);
return events;
}
/** 簇代表分低于最佳代表分该幅度时,整簇剪掉不扫(近似搜索:换来大幅减少裁剪加载) */
const PRUNE_MARGIN = 0.35;
/**
* 聚类感知的扫描顺序:先评各簇代表(medoid)得分,簇按分数降序排列,
* 远簇整体剪枝;未入簇字体(新上传)附在末尾不剪。
* medoid 评分走 matchFontEvents 慢路径(事件缓存命中后重扫很便宜)。
*/
async function orderFontsByCluster(
fonts: string[],
clusters: FontCluster[],
queryGlyphs: ParsedQueryGlyph[],
): Promise<{ order: string[]; pruned: Set<string> }> {
const medoidScore = new Map<string, number>();
for (const cluster of clusters) {
let sum = 0;
let n = 0;
try {
for (const event of await matchFontEvents(cluster.medoid, queryGlyphs)) {
if (event.type === "glyph" && event.glyph) {
sum += event.glyph.score;
n++;
}
}
} catch (err) {
console.error(`[glyph-match] medoid ${cluster.medoid} 评分失败:`, err instanceof Error ? err.stack ?? err.message : String(err));
}
medoidScore.set(cluster.medoid, n > 0 ? sum / n : 0);
}
const sorted = [...clusters].sort(
(a, b) => (medoidScore.get(b.medoid) ?? 0) - (medoidScore.get(a.medoid) ?? 0),
);
const best = sorted[0] ? (medoidScore.get(sorted[0]!.medoid) ?? 0) : 0;
const order: string[] = [];
const pruned = new Set<string>();
for (const cluster of sorted) {
const score = medoidScore.get(cluster.medoid) ?? 0;
if (score < best - PRUNE_MARGIN) {
for (const member of cluster.members) pruned.add(member);
continue;
}
/** medoid 评分阶段已填充事件缓存,扫描阶段重扫走缓存命中,成本远低于首次裁剪 */
order.push(cluster.medoid, ...cluster.members.filter((m) => m !== cluster.medoid));
}
const clustered = new Set(clusters.flatMap((c) => c.members));
for (const font of fonts) {
if (!clustered.has(font)) order.push(font);
}
return { order, pruned };
}
/**
* 全库搜索事件收集:串行逐字体处理,一次性返回全部事件。
* 不用 async generator / worker 池 / ReadableStream:LLRT 0.8/0.9 下这些原语
* 在高频穿插中会非确定性饿死(单次 next 挂上百秒)甚至 native segfault,
* 串行普通循环 + 整体返回是最稳的形态。
*/
async function collectMatchEvents(
fonts: string[],
pruned: Set<string>,
queryGlyphs: ParsedQueryGlyph[],
): Promise<GlyphMatchEvent[]> {
const all: GlyphMatchEvent[] = [{ type: "start", total: fonts.length + pruned.size }];
for (const font of pruned) {
all.push({ type: "fontDone", font });
}
for (const font of fonts) {
try {
all.push(...(await matchFontEvents(font, queryGlyphs)));
} catch (err) {
/** 单个字体裁剪/解析失败不拖垮整个搜索,记录后继续下一个 */
console.error(`[glyph-match] ${font} 处理失败:`, err instanceof Error ? err.stack ?? err.message : String(err), err);
}
all.push({ type: "fontDone", font });
}
all.push({ type: "done" });
return all;
}
export async function handleGlyphMatch(req: Request, _res: Response) {
@ -189,22 +343,26 @@ export async function handleGlyphMatch(req: Request, _res: Response) {
}
const fonts = await listCandidateFonts();
/** 聚类可用时按簇序扫描 + 剪枝;不可用退回目录顺序全量扫,并触发后台重建聚类 */
const clusters = await loadClusters(fonts);
let scanOrder = fonts;
let pruned = new Set<string>();
if (clusters && clusters.length > 1) {
const t0 = Date.now();
({ order: scanOrder, pruned } = await orderFontsByCluster(fonts, clusters, queryGlyphs));
console.log(`[glyph-match] 聚类排序 ${Date.now() - t0}ms(剪枝 ${pruned.size})`);
} else if (!clusters) {
scheduleClusterBuild(fonts);
}
const encoder = new TextEncoder();
const events = streamMatches(fonts, queryGlyphs);
const stream = new ReadableStream<Uint8Array>({
async pull(controller) {
const { done, value } = await events.next();
if (done) {
controller.close();
return;
}
controller.enqueue(encoder.encode(`${JSON.stringify(value)}\n`));
},
async cancel() {
await events.return(undefined);
},
});
/** LLRT 的 Response 不支持 ReadableStream body(body 会变 undefined),流挂在附加属性上由 HTTP 层写出 */
const events = await collectMatchEvents(scanOrder, pruned, queryGlyphs);
/**
* 一次性收集全部事件再返回完整 NDJSON body(不流式)。
* LLRT 的 ReadableStream pull + pipeTo 在高频穿插下存在非确定性
* 卡死/崩溃(0.8/0.9 均复现),评分本身已亚秒级,牺牲渐进展示换稳定。
* 前端逐行解析 NDJSON 的逻辑对完整 body 同样兼容。
*/
const responseBody = encoder.encode(events.map((event) => `${JSON.stringify(event)}\n`).join(""));
const res = new Response(null, {
status: 200,
headers: {
@ -214,6 +372,7 @@ export async function handleGlyphMatch(req: Request, _res: Response) {
"Connection": "close",
},
});
(res as Response & { _stream?: ReadableStream<Uint8Array> })._stream = stream;
/** 直接挂 body bytes:走 server 层的直接写回通道(含 Content-Length),绕开 LLRT blob 挂起 */
(res as Response & { _bodyBytes?: Uint8Array })._bodyBytes = responseBody;
return { req, res };
}

View File

@ -1,7 +1,11 @@
import "web-streams-polyfill/polyfill";
import { implInterface } from "../interface";
import * as fs from "fs/promises";
/**
* 不再引入 web-streams-polyfill:polyfill 覆盖原生 ReadableStream/WritableStream
* 后,与 LLRT 原生 socket/net 的组合会出现非确定性写挂起、数据串扰
* (响应 body 混入别的连接的 HTTP 头)等问题;LLRT 自带 WHATWG streams。
/**
* LLRT 的 fs 适配层
*

View File

@ -4,7 +4,8 @@ import { stat as fsStat, readFile, writeFile, readdir as fsReaddir, mkdir, unlin
implInterface({
async stat(path) {
const r = await fsStat(path);
return { ...r, isDirectory: () => r.isDirectory() };
/** Stats 的 isFile/isDirectory 在原型上,{...r} 展开会丢失,必须显式包装 */
return { ...r, isFile: () => r.isFile(), isDirectory: () => r.isDirectory() };
},
readFile(path) {
return readFile(path);

View File

@ -176,16 +176,26 @@ async function connectionHandle(
const rawRes = new Response();
const { res } = await handle(rawReq, rawRes);
/** 路由直接挂载的响应体(Uint8Array):免去 LLRT 下 res.blob() 的非确定性挂起 */
const bodyBytes = (res as Response & { _bodyBytes?: Uint8Array })._bodyBytes;
const resWriter = connection.writable.getWriter();
let headerText: string[] = [];
const headerText: string[] = [];
if (bodyBytes) headerText.push(`Content-Length: ${bodyBytes.length}`);
res.headers.forEach((value, key) => {
headerText.push(`${key}: ${value}`);
});
const resHeaertText = `HTTP/1.1 ${res.status} OK\r\n${headerText.join("\r\n")}\r\n\r\n`;
await resWriter.write(encoder.encode(resHeaertText));
/** LLRT 的 Response 不支持流 body,流式路由通过附加属性传递 */
const stream = (res as Response & { _stream?: ReadableStream<Uint8Array> })._stream ?? res.body;
if (stream) {
if (bodyBytes) {
/** header+body 合并单次 write:LLRT 的多次 write/close 组合会非确定性挂起 */
const head = encoder.encode(resHeaertText);
const frame = new Uint8Array(head.length + bodyBytes.length);
frame.set(head);
frame.set(bodyBytes, head.length);
await resWriter.write(frame);
resWriter.releaseLock();
} else if (stream) {
/** 流式响应:pipeTo 自行管理 writer 生命周期,结束后负责关闭流 */
resWriter.releaseLock();
await stream.pipeTo(connection.writable, { preventClose: false });

View File

@ -39,22 +39,14 @@ export function createTcpServer(
// 创建 WritableStream
const writable = new WritableStream<Uint8Array>({
write(chunk) {
return new Promise<void>((resolve, reject) => {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
socket.write(buffer, (err) => {
if (err) {
/** EPIPE:客户端已断开,销毁连接而非让异常向上冒泡打死进程 */
if ((err as NodeJS.ErrnoException).code === "EPIPE") {
socket.destroy();
resolve();
} else {
reject(err);
}
} else {
resolve();
}
});
});
/**
* 不等待 write 回调:LLRT 的 net shim 回调会间歇性丢失,
* promise 永不 resolve 导致响应写出非确定性挂起(0 bytes / 半截)。
* 响应体均为小帧(KB 级),socket 缓冲足够;错误由 error 事件兜底。
*/
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
socket.write(buffer);
return Promise.resolve();
},
close() {
socket.end();
@ -66,8 +58,8 @@ export function createTcpServer(
// 实现 close 方法
function close() {
/** 只 end 不 destroy:destroy 会立即丢弃写缓冲中未发送的数据,导致响应截断 */
socket.end();
socket.destroy();
}
onSocket({ readable, writable, close });

View File

@ -0,0 +1,42 @@
/**
* 全量预建字形索引:遍历字体目录,逐字体构建 .gidx(走内存闸门,一次一个)。
* 用法:pnpm exec tsx scripts/build_glyph_index.ts
*/
import "../backend/server/node";
import { readdir } from "../backend/interface";
import { fontDirs } from "../backend/config";
import { buildGlyphIndex } from "../backend/font_util/glyph_index";
async function main() {
const started = Date.now();
let built = 0;
let failed = 0;
for (const dir of fontDirs) {
let entries: { name: string; isFile: () => boolean }[];
try {
entries = await readdir(dir);
} catch {
continue;
}
for (const entry of entries) {
if (!entry.isFile() || !/\.(ttf|otf)$/i.test(entry.name)) continue;
const fontPath = `${dir}/${entry.name}`;
try {
const ok = await buildGlyphIndex(fontPath);
if (ok) {
built++;
console.log(`[${built}] ${entry.name} ✓`);
} else {
failed++;
console.log(`[skip] ${entry.name} 无有效字形`);
}
} catch (err) {
failed++;
console.error(`[fail] ${entry.name}:`, err instanceof Error ? err.message : err);
}
}
}
console.log(`完成:构建 ${built},失败 ${failed},耗时 ${((Date.now() - started) / 1000).toFixed(1)}s`);
}
main();

View File

@ -10,7 +10,7 @@
*/
import { ref, computed, useTemplateRef } from "vue";
import { usePageSeo } from "../useSeo";
import { prepareQueryGlyphs, renderSubsetGlyphPreviews, base64ToBytes } from "../font-finder/matcher";
import { prepareQueryGlyphs, renderSubsetGlyphPreviews } from "../font-finder/matcher";
/** 服务端逐字返回的单字体结果(与 backend/routes/glyph_match.ts 的 NDJSON 事件对齐) */
interface ServerFontResult {
@ -212,30 +212,43 @@ function onGlyphInput() {
results.value = [];
}
/** 裁剪接口生成的字体预览缓存(同字体同字只渲染一次,来自流事件的 woff2) */
/** 裁剪接口生成的字体预览缓存(同字体同字只渲染一次) */
const glyphPreviewCache = new Map<string, string>();
/** 预览缓存更新计数器:Map 非响应式,用它触发模板重渲染 */
const previewTick = ref(0);
function serverGlyphPreview(font: string, char: string): string {
void previewTick.value;
return glyphPreviewCache.get(font + "|" + char) ?? "";
}
/** 已请求过预览的字体集合(每次搜索重置) */
const previewRequested = new Set<string>();
/** 对排在前面的结果按需拉取裁剪字体并渲染预览(避免全库搜索时传输所有字体的子集包) */
function requestPreviews(topN = 12) {
const chars = [...new Set(filledGlyphIndices.value.map((i) => glyphChars.value[i]!))];
if (!chars.length) return;
const text = chars.join("");
for (const r of results.value.slice(0, topN)) {
if (previewRequested.has(r.font)) continue;
previewRequested.add(r.font);
void fetch(`/api?font=${encodeURIComponent(r.font)}&text=${encodeURIComponent(text)}&outType=woff2`)
.then((res) => (res.ok ? res.arrayBuffer() : Promise.reject(new Error(`HTTP ${res.status}`))))
.then((buf) => renderSubsetGlyphPreviews(new Uint8Array(buf), chars))
.then((previews) => {
for (const [char, preview] of previews) glyphPreviewCache.set(r.font + "|" + char, preview);
previewTick.value++;
})
.catch(() => previewRequested.delete(r.font));
}
}
/** 结果中的查询序号 → 原始图块预览,留空图块与候选字体缺字均不会造成错位 */
function queryPreview(queryIndex: number): string {
const sourceIndex = filledGlyphIndices.value[queryIndex];
return sourceIndex === undefined ? "" : (glyphPreviews.value[sourceIndex] ?? "");
}
/** 收到 font 事件后异步渲染预览:直接消费流携带的 woff2,不再二次请求裁剪接口 */
function renderPreviewsFromEvent(font: string, subsetB64: string) {
const woff2 = base64ToBytes(subsetB64);
const chars = filledGlyphIndices.value.map((i) => glyphChars.value[i]!);
void renderSubsetGlyphPreviews(woff2, chars).then((previews) => {
for (const [char, preview] of previews) {
glyphPreviewCache.set(font + "|" + char, preview);
}
});
}
/** 新的单字分数到达后重算平均分并按分数降序重排,让最像的字体始终在顶部 */
/** 新的单字分数到达后重算平均分并按分数降序重排,让最像的字体始终在顶部;同步懒加载前排预览 */
function resortResults() {
for (const r of results.value) {
r.score = r.glyphs.length
@ -243,6 +256,7 @@ function resortResults() {
: 0;
}
results.value = [...results.value].sort((a, b) => b.score - a.score);
requestPreviews();
}
/** 开始识别:NDJSON 流式请求,识别一个字即可看到一个字的结果 */
@ -251,6 +265,7 @@ async function startMatch() {
matching.value = true;
errorMsg.value = "";
results.value = [];
previewRequested.clear();
doneCount.value = 0;
totalCount.value = 0;
const t0 = performance.now();
@ -283,7 +298,6 @@ async function startMatch() {
const item: ServerFontResult = { font: event.font, score: 0, missing: false, glyphs: [] };
byFont.set(event.font, item);
results.value.push(item);
renderPreviewsFromEvent(event.font, event.subset);
break;
}
case "glyph": {
@ -341,7 +355,10 @@ const scoreColor = (s: number) => (s > 0.9 ? "#16a34a" : s > 0.8 ? "#d97706" : "
<template>
<div style="max-width: 960px; margin: 0 auto; padding: 24px 16px 64px" @paste="onPaste">
<h1 style="font-size: 26px; margin: 0 0 8px">截图找字体</h1>
<div style="display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap">
<h1 style="font-size: 26px; margin: 0">截图找字体</h1>
<a href="/" style="color: #1677ff; font-size: 14px; text-decoration: none" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'">← 返回首页</a>
</div>
<p style="color: #666; margin: 0 0 20px; font-size: 14px">
上传含文字的截图,与站内字体库比对,找出最相似的字体。
</p>