客户端设备识别(Device)
离线解析 HTTP 请求的 User-Agent 与现代浏览器 Sec-CH-UA* Client Hints,输出终端形态、品牌、型号、操作系统、浏览器与内核、App 内嵌 WebView 及爬虫画像。插件零外部网络依赖、内置高覆盖率预编译规则集与有界 LRU 缓存,支持加载兼容外部 JSON 格式的规则快照并通过 device-update 后台校验原子热更新。
快速接入#
在 Cargo.toml 开启主包 kxed 的 device 特性(需要后台定时拉取外部规则快照时改开 device-update,自动包含 http-client):
[dependencies]
kxed = { version = "0.0.5-alpha", features = ["device"] }注册 DevicePlugin::new() 后,可直接在原生路由 handler 中提取 DeviceInfo / ClientHints,或在 Procedure 中调用 ctx.detect_headers(&headers) / ctx.detect_user_agent(ua):
use kxed::plugins::device::{ClientHints, DeviceInfo, DevicePlugin};
use kxed::prelude::*;
async fn device_profile(info: DeviceInfo, hints: ClientHints) -> String {
format!(
"kind={} os={:?} browser={:?} mobile={} has_hints={}",
info.device_type.as_str(),
info.os_name,
info.browser_name,
info.is_mobile,
!hints.is_empty(),
)
}
#[query(name = "analytics.parse_ua", public)]
pub async fn parse_ua(ctx: &AppCtx, ua: String) -> Result<DeviceInfo, AppErr> {
ctx.detect_user_agent(&ua)
}
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.plugin(DevicePlugin::new())
.routes(|router| {
router.route("/api/device", get(device_profile));
})
.run()
.await
}核心用法#
User-Agent 与 Client Hints 融合识别#
随着主流浏览器冻结 User-Agent 中的机型与系统小版本,优先使用 detect_headers(&headers)(或 Axum 提取器 DeviceInfo)同时融合 User-Agent 与 RFC 8941 结构化 Sec-CH-UA* 请求头:
- 提取的 Client Hints 字段:
Sec-CH-UA(品牌列表)、Sec-CH-UA-Full-Version-List(优先提供完整浏览器版本)、Sec-CH-UA-Mobile(?1/?0移动态)、Sec-CH-UA-Platform、Sec-CH-UA-Platform-Version与Sec-CH-UA-Model(还原被冻结为K的 Android 真实机型)。 - 独立提取器:
ClientHints实现了无失败的FromRequestParts,即使未注册DevicePlugin也可在 handler 中直接提取;DeviceInfo提取器依赖已注册的DevicePlugin。 - 离线纯内存调用:单测或批处理脚本可直接构造
DeviceDetector::builtin(),调用detect(ua, &hints)、detect_user_agent(ua)、reload_from_json(bytes)、snapshot_version()、rule_count()与clear_cache()。
输出字段说明#
DeviceInfo 标记为 #[non_exhaustive],完整描述一次识别结果:
| 字段 | 类型 | 说明 |
|---|---|---|
device_type | DeviceKind | 设备形态:desktop、smartphone、tablet、bot、console、tv、wearable、unknown |
brand / model | Option<String> | 设备品牌(如 Apple、Huawei、Xiaomi、OPPO、vivo)与具体型号 |
os_name / os_version | Option<String> | 操作系统名(如 iOS、Android、HarmonyOS、Windows、macOS)与版本 |
browser_name / browser_version / engine | Option<String> | 浏览器名、完整或主版本号与排版引擎(如 Blink、WebKit、Gecko、ArkWeb) |
app_name / is_webview | Option<String> / bool | 识别到的宿主 App(如 WeChat、Alipay、Douyin、Xiaohongshu、Lark)及内嵌 WebView 标记 |
is_bot / bot_name | bool / Option<String> | 是否为爬虫、监控探针或自动化脚本及其名称 |
is_mobile | bool | 是否为手机、平板或显式声明移动态的终端 |
外部规则快照与后台原子热更新#
内置规则已开箱覆盖主流桌面、移动端、国产机型、常见 App WebView 与爬虫;如需快速跟进新机型或自定义内部客户端,可提供外部 JSON 规则快照(RuleSnapshot,包含 version、bots、apps、oss、browsers、devices 与按品牌分组的 brands):
- 安全与性能护栏:单条 UA 送入正则匹配前先按
device.max_ua_bytes(默认1024字节)在 UTF-8 字符边界截断;单份规则快照不得超过device.update.max_rules_bytes(上限 16 MiB),单条正则与总规则数均受硬上限(MAX_REGEX_PATTERN_BYTES、MAX_TOTAL_RULES)保护,且编译后使用线性时间 DFA 引擎无回溯 ReDoS 风险。 - 后台热更新(
device-update):开启device-update、注册HttpClientPlugin并配置device.update.url后,后台任务每隔device.update.interval带If-None-Match(ETag)拉取新快照;若配置了device.update.sha256先执行常量时间 SHA-256 校验,再在阻塞线程池完成 JSON 解析与正则预编译,全部校验通过后才经ArcSwap无锁替换规则集并清空旧 LRU 缓存;如同时配置了device.rules_path,会先落同目录临时文件fsync再原子rename持久化。任何下载、摘要或规则错误均保留旧规则继续服务。
配置#
| 键 | 缺省 | 范围与含义 |
|---|---|---|
device.rules_path | 空 | 可选外部 JSON 规则快照路径;未配置时仅用内置规则 |
device.max_ua_bytes | 1024 | 单条 UA 送入匹配前的截断字节上限,范围 64..=16384 |
device.cache_capacity | 16384 | 进程内有界 LRU 缓存容量(以 UA 与 Client Hints 组合为键),0 为关闭,上限 1000000 |
device.builtin_fallback | true | 加载外部规则后,外部规则未命中的维度是否回退内置默认规则 |
device.update.url | 空 | 远程规则快照下载地址(SecretString,日志与 config show 脱敏,须 http:// 或 https://) |
device.update.interval | 24h | 后台热更新轮询周期,范围 10ms..=365d |
device.update.timeout | 30s | 单次拉取外部规则快照的 HTTP 超时,范围 100ms..=5m |
device.update.sha256 | 空 | 可选 64 位十六进制 SHA-256 摘要,不匹配直接拒收 |
device.update.max_rules_bytes | 16777216(16 MiB) | 单份外部规则快照允许的最大字节数,范围 1024..=67108864(64 MiB) |
错误码、多实例与 Prometheus 指标#
- 错误码映射:
DeviceError::InvalidRules映射为 422device_invalid_rules;DeviceError::DigestMismatch映射为 502device_digest_mismatch;DeviceError::RulesIo与DeviceError::UpdateFailed映射为 500device_rules_failed/device_update_failed。 - 多实例部署:每个实例在进程内独立持有只读编译规则与 LRU 缓存,无跨节点锁竞争;多实例共用本地
device.rules_path时采用独立临时文件原子rename互不覆盖,大集群建议把规则快照托管在内部对象存储或静态文件 CDN 上并启用 ETag 304 协商。
| 指标 | 类型与标签 | 含义 |
|---|---|---|
kxed_device_lookup_total | Counter(outcome) | 设备识别总次数(matched / bot / unknown) |
kxed_device_cache_hit_total | Counter | LRU 缓存命中次数 |
kxed_device_cache_miss_total | Counter | LRU 缓存未命中次数 |
kxed_device_rules_reload_total | Counter(outcome) | 规则热更新与手动重载结果计数(reloaded / not_modified / invalid / failed) |