mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-23 03:19:41 +00:00
重复设备行读不出来,顺带修好测试页丢设备标识
同一台设备被填过两种写法时,迁移会把两行刷成同一个地址, 之后上报和激活都撞上,设备彻底读不出来还查不到原因。 改成撞上的行整组不动、查询取第一条;测试页发设备标识的那段 把横线写成了区间,大写地址会被算成空串,一并修好。
This commit is contained in:
parent
71d9084af9
commit
6562476c78
5 changed files with 393 additions and 110 deletions
|
|
@ -1073,18 +1073,52 @@ def test_issued_after_future_timestamp_degrades():
|
|||
|
||||
|
||||
def test_reload_order_keeps_config_intact_on_bad_auth():
|
||||
"""10g. 换配置时先校验认证段:配错不能留下"配置换了一半、模块不再重建"的状态"""
|
||||
ws_server = build_ws_server(build_config(enabled=True, allowed=[ALLOWED_MAC]))
|
||||
before = ws_server.config
|
||||
broken = build_config(enabled=True)
|
||||
broken["server"]["auth"]["allowed_devices"] = "aa:bb:cc:dd:ee:ff"
|
||||
"""10g. 换配置时先校验认证段:配错不能留下"配置换了一半、模块不再重建"的状态
|
||||
|
||||
try:
|
||||
ws_server._load_auth_config(broken)
|
||||
raise AssertionError("配错的 auth 段应抛错")
|
||||
except ValueError:
|
||||
pass
|
||||
assert ws_server.config is before, "校验没过就不该动 self.config"
|
||||
走真的 update_config():只直接调 _load_auth_config 的话,这条用例自己就断言了
|
||||
"self.config 没被换",可被测代码根本没走到赋值那一步,怎么改都能过。
|
||||
真正要验的是校验抛错后 self.config 仍指向老对象、且模块没有重建过。
|
||||
"""
|
||||
import config.config_loader as loader
|
||||
import core.websocket_server as ws_mod
|
||||
|
||||
ws_server = build_ws_server(build_config(enabled=True, allowed=[ALLOWED_MAC]))
|
||||
ws_server.config_lock = asyncio.Lock()
|
||||
before = ws_server.config
|
||||
|
||||
# 接口真的返回了配错的 auth 段:allowed_devices 是标量字符串,set() 会逐字符拆开
|
||||
broken = {
|
||||
"selected_module": [],
|
||||
"server": {
|
||||
"ip": "10.0.0.9",
|
||||
"auth": {"enabled": True, "allowed_devices": "aa:bb:cc:dd:ee:ff"},
|
||||
},
|
||||
}
|
||||
# 模块重建是这条用例真正盯的副作用,校验没过就不该被触发
|
||||
rebuilt = []
|
||||
fake_modules = lambda *a, **k: (rebuilt.append(a[2]) or {})
|
||||
|
||||
async def fake_get_server_config():
|
||||
return {k: (v.copy() if isinstance(v, dict) else v) for k, v in broken.items()}
|
||||
|
||||
with patch.object(loader, "read_config", return_value={}), patch.object(
|
||||
loader, "get_project_dir", return_value="/tmp/"
|
||||
), patch.object(loader, "init_service"), patch.object(
|
||||
loader, "get_server_config", fake_get_server_config
|
||||
), patch.object(
|
||||
ws_mod, "initialize_modules", fake_modules
|
||||
), patch.object(
|
||||
ws_mod, "check_vad_update", return_value=False
|
||||
), patch.object(
|
||||
ws_mod, "check_asr_update", return_value=False
|
||||
):
|
||||
ok = asyncio.run(ws_server.update_config())
|
||||
|
||||
assert ok is False, "认证段配错时 update_config 应返回失败"
|
||||
assert ws_server.config is before, (
|
||||
f"校验没过 self.config 就被换掉了:{ws_server.config['server']}"
|
||||
)
|
||||
assert rebuilt == [], f"校验没过还重建了模块:{rebuilt}"
|
||||
print("OK: 认证段校验失败时配置保持原样")
|
||||
|
||||
|
||||
|
|
@ -1239,31 +1273,197 @@ def test_tester_page_covers_both_localhost_spellings():
|
|||
print("OK: 文档写清了测试页的两种来源")
|
||||
|
||||
|
||||
def test_tester_page_reuses_token():
|
||||
"""10l. 测试页拿到 token 要存下来复用,激活码用一次就作废"""
|
||||
connector = open(
|
||||
os.path.join(REPO, "main", "digital-human", "js", "core", "network", "ota-connector.js"),
|
||||
encoding="utf-8",
|
||||
).read()
|
||||
manager = open(
|
||||
os.path.join(REPO, "main", "digital-human", "js", "config", "manager.js"),
|
||||
encoding="utf-8",
|
||||
).read()
|
||||
TESTER_JS = os.path.join(REPO, "main", "digital-human", "js")
|
||||
TESTER_JS_FILES = (
|
||||
"utils/logger.js",
|
||||
"config/manager.js",
|
||||
"core/network/ota-connector.js",
|
||||
)
|
||||
|
||||
assert "xz_tester_token" in connector, "OTA 拿到的 token 没存下来"
|
||||
assert "config.token || config.activationCode" in connector, (
|
||||
"发 OTA 时应优先用 token,没有才用激活码"
|
||||
# 在 node 里真跑一遍测试页的连接流程:填激活码 → 连接 → 刷新 → 再连。
|
||||
# 只跑 ota-connector 和 manager 这两个模块,其余依赖靠下面的桩顶掉。
|
||||
TESTER_DRIVER = r"""
|
||||
function makeStorage() {
|
||||
const m = new Map();
|
||||
return {
|
||||
getItem: k => (m.has(k) ? m.get(k) : null),
|
||||
setItem: (k, v) => m.set(k, String(v)),
|
||||
removeItem: k => m.delete(k),
|
||||
_dump: () => Object.fromEntries(m),
|
||||
};
|
||||
}
|
||||
globalThis.sessionStorage = makeStorage();
|
||||
globalThis.localStorage = makeStorage();
|
||||
globalThis.window = { location: { origin: 'http://127.0.0.1:8006' } };
|
||||
|
||||
const inputs = {
|
||||
deviceMac: { value: '' },
|
||||
deviceName: { value: '' },
|
||||
clientId: { value: '' },
|
||||
otaUrl: { value: 'http://127.0.0.1:8002/ota/' },
|
||||
wakewordWsUrl: { value: '' },
|
||||
wakewordEnabled: { value: 'true' },
|
||||
wakewordList: { value: '' },
|
||||
emojiEnabled: { value: 'true' },
|
||||
activationCode: { value: '' },
|
||||
serverUrl: { value: '' },
|
||||
};
|
||||
globalThis.document = { getElementById: id => inputs[id] || null };
|
||||
|
||||
const calls = [];
|
||||
let issued = process.env.ISSUED_FIRST;
|
||||
globalThis.fetch = async (url, opts) => {
|
||||
calls.push({ url, headers: opts.headers, body: JSON.parse(opts.body) });
|
||||
return {
|
||||
ok: true, status: 200, statusText: 'OK',
|
||||
json: async () => ({ websocket: { url: 'ws://127.0.0.1:8000/', token: issued } }),
|
||||
};
|
||||
};
|
||||
class FakeWebSocket {
|
||||
constructor(url, protocols) {
|
||||
this.url = url;
|
||||
this.protocols = protocols;
|
||||
FakeWebSocket.last = this;
|
||||
}
|
||||
}
|
||||
globalThis.WebSocket = FakeWebSocket;
|
||||
|
||||
const { webSocketConnect } = await import('./js/core/network/ota-connector.js');
|
||||
const { loadConfig, saveConfig, getConfig } = await import('./js/config/manager.js');
|
||||
|
||||
const mac = process.env.TESTER_MAC;
|
||||
loadConfig();
|
||||
inputs.deviceMac.value = mac;
|
||||
inputs.deviceName.value = '测试机';
|
||||
inputs.clientId.value = 'client-1';
|
||||
inputs.activationCode.value = process.env.ACTIVATION_CODE;
|
||||
saveConfig();
|
||||
|
||||
// 页面上点连接按钮之前会再 loadConfig 一次,走的是同一条读回路径
|
||||
loadConfig();
|
||||
await webSocketConnect('http://127.0.0.1:8002/ota/', getConfig());
|
||||
const first = {
|
||||
call: calls[calls.length - 1],
|
||||
session: sessionStorage._dump(),
|
||||
local: localStorage._dump(),
|
||||
};
|
||||
|
||||
// 刷新页面:server 端激活码已作废,只有 token 能续签
|
||||
issued = process.env.ISSUED_SECOND;
|
||||
loadConfig();
|
||||
await webSocketConnect('http://127.0.0.1:8002/ota/', getConfig());
|
||||
const second = {
|
||||
call: calls[calls.length - 1],
|
||||
session: sessionStorage._dump(),
|
||||
local: localStorage._dump(),
|
||||
protocols: FakeWebSocket.last.protocols,
|
||||
};
|
||||
|
||||
// logger 会往 stdout 写行,JSON 用标记包起来单独取
|
||||
process.stdout.write('<<<JSON' + JSON.stringify({ first, second, mac }) + '\n');
|
||||
"""
|
||||
|
||||
|
||||
def run_tester_page(mac: str, activation_code: str, issued_first: str, issued_second: str) -> dict:
|
||||
"""在 node 里跑一遍测试页的连接流程,返回实际发出去的请求和落库的凭证"""
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
work = tempfile.mkdtemp(prefix="check_auth_3448_js_")
|
||||
try:
|
||||
# node 按 ESM 加载,import 上的 ?v=0205 是浏览器缓存标记,磁盘上不存在这个文件
|
||||
for rel in TESTER_JS_FILES:
|
||||
dest = os.path.join(work, "js", rel)
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
with open(os.path.join(TESTER_JS, rel), encoding="utf-8") as fh:
|
||||
body = re.sub(r"(\.js)\?v=\d+", r"\1", fh.read())
|
||||
with open(dest, "w", encoding="utf-8") as fh:
|
||||
fh.write(body)
|
||||
|
||||
driver = os.path.join(work, "driver.mjs")
|
||||
with open(driver, "w", encoding="utf-8") as fh:
|
||||
fh.write(TESTER_DRIVER)
|
||||
|
||||
env = dict(
|
||||
os.environ,
|
||||
TESTER_MAC=mac,
|
||||
ACTIVATION_CODE=activation_code,
|
||||
ISSUED_FIRST=issued_first,
|
||||
ISSUED_SECOND=issued_second,
|
||||
)
|
||||
proc = subprocess.run(
|
||||
["node", driver], capture_output=True, text=True, env=env, timeout=120
|
||||
)
|
||||
assert proc.returncode == 0, f"node 跑测试页失败:{proc.stderr[-2000:]}"
|
||||
payload = [
|
||||
line for line in proc.stdout.splitlines() if line.startswith("<<<JSON")
|
||||
]
|
||||
assert payload, f"node 没吐出结果:{proc.stdout[-2000:]}"
|
||||
return json.loads(payload[0][len("<<<JSON") :])
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def test_tester_page_reuses_token():
|
||||
"""10l. 测试页拿到 token 要存下来复用,激活码用一次就作废
|
||||
|
||||
真在 node 里跑页面那条连接链,看实际发出去的 Authorization 和落库的凭证。
|
||||
原来是 grep 子串,只能证明代码里出现过这几个词,证明不了第二次连用的是 token。
|
||||
"""
|
||||
out = run_tester_page(
|
||||
mac="AA:BB:CC:DD:EE:FF",
|
||||
activation_code="CODE-1",
|
||||
issued_first="TOKEN-1",
|
||||
issued_second="TOKEN-2",
|
||||
)
|
||||
assert "xz_tester_activationCode" in manager and "loadConfig" in manager
|
||||
load_config_body = manager.split("export function loadConfig")[1].split("export function")[0]
|
||||
assert "xz_tester_activationCode" in load_config_body, (
|
||||
"激活码只写不读,刷新页面就断了"
|
||||
first, second = out["first"], out["second"]
|
||||
|
||||
assert first["call"]["headers"].get("Authorization") == "Bearer CODE-1", (
|
||||
f"首次应拿激活码换 token:{first['call']['headers']}"
|
||||
)
|
||||
assert first["session"].get("xz_tester_token") == "TOKEN-1", (
|
||||
f"下发的 token 没存进 sessionStorage:{first['session']}"
|
||||
)
|
||||
assert first["local"].get("xz_tester_token") == "TOKEN-1", (
|
||||
f"刷新页面就没了,token 得存进 localStorage:{first['local']}"
|
||||
)
|
||||
assert second["call"]["headers"].get("Authorization") == "Bearer TOKEN-1", (
|
||||
f"刷新后应拿上次的 token 续签,不是作废的激活码:{second['call']['headers']}"
|
||||
)
|
||||
assert second["session"].get("xz_tester_token") == "TOKEN-2", (
|
||||
f"续签换的新 token 应覆盖旧的:{second['session']}"
|
||||
)
|
||||
assert "t-TOKEN-2" in second["protocols"], (
|
||||
f"凭证要靠子协议带给 websocket 连接:{second['protocols']}"
|
||||
)
|
||||
get_config_body = manager.split("export function getConfig")[1].split("// 保存连接URL")[0]
|
||||
assert "xz_tester_token" in get_config_body, "存下来的 token 没传下去"
|
||||
print("OK: 测试页会复用 token,激活码也读得回来")
|
||||
|
||||
|
||||
def test_tester_page_sends_normalized_device_id():
|
||||
"""10m. 大写 MAC 要发出小写去分隔符的 Device-Id,且与子协议头一致
|
||||
|
||||
测试页自己生成的随机 MAC 就是大写。这里曾写成 /[:-_]/g,那是 : 到 _ 的字符区间,
|
||||
连大写 A-Z 一起吃掉,大写 MAC 算出来是空串。服务端只收 d- 后面非空的值,
|
||||
空的话连接直接被判成"端口探测"关掉,测试页连都连不上。
|
||||
"""
|
||||
out = run_tester_page(
|
||||
mac="AA:BB:CC:DD:EE:FF",
|
||||
activation_code="CODE-1",
|
||||
issued_first="TOKEN-1",
|
||||
issued_second="TOKEN-2",
|
||||
)
|
||||
want = "aabbccddeeff"
|
||||
for phase in ("first", "second"):
|
||||
got = out[phase]["call"]["headers"].get("Device-Id")
|
||||
assert got == want, f"{phase} 的 Device-Id 应是 {want},实际 {got!r}"
|
||||
assert f"d-{want}" in out["second"]["protocols"], (
|
||||
f"子协议头和请求头得是同一个值,否则 token 签名对不上:{out['second']['protocols']}"
|
||||
)
|
||||
print("OK: 大写 MAC 归一后才发出去,两处一致")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_allowed_mac_without_token_rejected()
|
||||
test_allowed_mac_forged_client_id_rejected()
|
||||
|
|
@ -1315,6 +1515,7 @@ def main() -> int:
|
|||
test_cors_empty_warn_reports_blocked_origin()
|
||||
test_tester_page_covers_both_localhost_spellings()
|
||||
test_tester_page_reuses_token()
|
||||
test_tester_page_sends_normalized_device_id()
|
||||
print("\nALL PASS: 3448 认证旁路已关闭")
|
||||
return 0
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import { log } from '../../utils/logger.js?v=0205';
|
||||
|
||||
// 子协议值必须是合法的 token 字符,冒号不在其中,所以 Device-Id 去掉分隔符。
|
||||
// OTA 请求头与 websocket 子协议必须用同一个值,否则 token 签名对不上
|
||||
// OTA 请求头与 websocket 子协议必须用同一个值,否则 token 签名对不上。
|
||||
// 方括号里横线必须写在最前面,写成 [:-_] 会当成 : 到 _ 的区间,
|
||||
// 连大写 A-Z 一起吃掉,大写 MAC 会被算成空串
|
||||
export function normalizeDeviceId(deviceId) {
|
||||
return (deviceId || '').replace(/[:-_]/g, '').toLowerCase();
|
||||
return (deviceId || '').replace(/[-:_]/g, '').toLowerCase();
|
||||
}
|
||||
|
||||
// WebSocket 连接
|
||||
|
|
@ -28,8 +30,9 @@ export async function webSocketConnect(otaUrl, config) {
|
|||
}
|
||||
|
||||
// token 存下来下次续签用:激活码用掉即作废,
|
||||
// 不存的话第二次点连接必然被服务端拒
|
||||
const issuedToken = (websocket.token || otaResult.mqtt?.token || '').replace(/^Bearer\s+/i, '');
|
||||
// 不存的话第二次点连接必然被服务端拒。
|
||||
// 响应里 websocket 和 mqtt 是二选一,带 mqtt 的响应走不到这里
|
||||
const issuedToken = (websocket.token || '').replace(/^Bearer\s+/i, '');
|
||||
if (issuedToken) {
|
||||
sessionStorage.setItem('xz_tester_token', issuedToken);
|
||||
localStorage.setItem('xz_tester_token', issuedToken);
|
||||
|
|
|
|||
|
|
@ -420,7 +420,14 @@ public class DeviceServiceImpl extends BaseServiceImpl<DeviceDao, DeviceEntity>
|
|||
private DeviceEntity selectByMacAddress(String macAddress) {
|
||||
QueryWrapper<DeviceEntity> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq("mac_address", macAddress);
|
||||
return baseDao.selectOne(wrapper);
|
||||
// 按 id 排一下再取第一条:同一份重复数据每次得拿到同一台,
|
||||
// 不然称呼和缓存键会跟着返回顺序变
|
||||
wrapper.orderByAsc("id");
|
||||
// 有重复行时 selectOne 直接抛 TooManyResultsException,报活和激活两条路一起崩,
|
||||
// 库里还看不出发生过什么。迁移对撞车的行整组不动,那种库会同时存在两行,
|
||||
// 取第一条让设备读得出来;两行归谁所有是人的判断,脚本不替人定
|
||||
List<DeviceEntity> devices = baseDao.selectList(wrapper);
|
||||
return devices.isEmpty() ? null : devices.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -2,80 +2,100 @@
|
|||
--
|
||||
-- 之前用户在智控台手填的 MAC 原样入库(可能是 AA-BB-… 、aabbcc… 或全大写),
|
||||
-- OTA 侧归一后按 aa:bb:… 精确查库,查不到就静默不发凭证、不下发固件。
|
||||
-- 这里把存量两列刷成归一后的形态。
|
||||
-- 这里把存量刷成归一后的形态。
|
||||
--
|
||||
-- 只改 ai_device.mac_address,不动 id:手填设备的 id 就是当时的原始 MAC,
|
||||
-- 改 id 会牵动外键和缓存键,风险大于收益。查不到归一值时查询侧会拿原文再试一次。
|
||||
-- mac_address 上只有普通索引不是唯一键,这段不会撞键。
|
||||
|
||||
UPDATE `ai_device`
|
||||
SET `mac_address` = LOWER(CONCAT(
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2)
|
||||
))
|
||||
WHERE `mac_address` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
|
||||
AND BINARY `mac_address` <> BINARY LOWER(CONCAT(
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2)
|
||||
));
|
||||
|
||||
-- 通讯录表的主键就是 (mac_address, target_mac),两段拼起来还是同一个 MAC 时会撞键。
|
||||
-- 撞键说明同一台设备在同一个人的通讯录里存了两条、只是写法不同,属于脏数据,
|
||||
-- 跑之前先看一眼下面这条,有结果就得先把重复的挑出来删掉:
|
||||
-- 只改 mac_address,不动 id:手填设备的 id 就是当时的原始 MAC,而 ai_chat_history
|
||||
-- 等表按 device_id 存着对话记录,改 id 会牵动这些外键和缓存键,风险大于收益。
|
||||
-- 查不到归一值时查询侧会拿原文再试一次。
|
||||
--
|
||||
-- SELECT LOWER(REPLACE(REPLACE(REPLACE(`mac_address`,':',''),'-',''),'_','')) AS nmac,
|
||||
-- LOWER(REPLACE(REPLACE(REPLACE(`target_mac`,':',''),'-',''),'_','')) AS ntmac,
|
||||
-- COUNT(*) c
|
||||
-- FROM `ai_device_address_book`
|
||||
-- GROUP BY nmac, ntmac HAVING c > 1;
|
||||
-- ⚠️ 三段都只刷「归一后全表只剩它一行」的那种,这不是保守,是必须。
|
||||
--
|
||||
-- 真撞上了会直接报 Duplicate entry 而不是把数据改坏,这时上面 ai_device 那段
|
||||
-- 已经生效了;把重复的清掉再跑一遍就行,两段都能重跑。
|
||||
-- 值已经是对的就整行跳过,重跑一遍是空操作。两段是分开判的:
|
||||
-- 只改本机地址不改对方地址的行,也要算进去,不然它会一直留着旧写法。
|
||||
-- 同一台设备被填过两种写法(AA-BB-CC-DD-EE-FF 和 aabbccddeeff)时,两行会归一成
|
||||
-- 同一个值,全刷就撞了。而两段撞了的后果完全不一样,方向是反的:
|
||||
--
|
||||
-- ai_device:mac_address 上只有普通索引不是唯一键,撞了数据库一声不吭。
|
||||
-- 两行一模一样存下来,之后 getDeviceByMacAddress 的 selectOne 命中多行直接抛
|
||||
-- TooManyResultsException。这台设备之后彻底读不出来,报活和激活两条路全崩,
|
||||
-- 库里没有任何东西能看出发生过什么,用户只看到一个错误响应。
|
||||
--
|
||||
-- ai_device_address_book:主键是 (mac_address, target_mac),撞上会报 Duplicate
|
||||
-- entry,整个 changeset 回滚,服务起不来。吵,但看得见。
|
||||
--
|
||||
-- 也就是没有 DB 保护的那段才会静默坏数据。下面每段的 cnt.n = 1 就是这个保护:
|
||||
-- 刷完不会出现两行同值。撞上的行一个都不动,保持迁移前的状态——写法不同就 eq 不到,
|
||||
-- 用户看得见、也还能重新添加,manualAddDevice 现在入库前会归一,重新添加会补上一行
|
||||
-- 归一后的。
|
||||
--
|
||||
-- ── ① ai_device.mac_address ────────────────────────────────────────────
|
||||
|
||||
UPDATE `ai_device_address_book`
|
||||
SET `mac_address` = LOWER(CONCAT(
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2)
|
||||
)),
|
||||
`target_mac` = LOWER(CONCAT(
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 11, 2)
|
||||
))
|
||||
WHERE `mac_address` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
|
||||
AND `target_mac` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
|
||||
AND (
|
||||
BINARY `mac_address` <> BINARY LOWER(CONCAT(
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2)
|
||||
))
|
||||
OR BINARY `target_mac` <> BINARY LOWER(CONCAT(
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 1, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 3, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 5, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 7, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 9, 2), ':',
|
||||
SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 11, 2)
|
||||
))
|
||||
);
|
||||
WITH norm AS (
|
||||
SELECT `id`, LOWER(CONCAT(SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2))) AS `nmac`
|
||||
FROM `ai_device`
|
||||
WHERE `mac_address` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
|
||||
),
|
||||
cnt AS (SELECT `nmac`, COUNT(*) AS `n` FROM norm GROUP BY `nmac`)
|
||||
UPDATE `ai_device` d
|
||||
JOIN norm ON norm.`id` = d.`id`
|
||||
JOIN cnt ON cnt.`nmac` = norm.`nmac`
|
||||
SET d.`mac_address` = norm.`nmac`
|
||||
WHERE cnt.`n` = 1
|
||||
-- BINARY 是逐字节比:ai_device 走的是库的 utf8mb4_0900_ai_ci,
|
||||
-- 普通 <> 认为 AA:BB:… 和 aa:bb:… 相等,大写行会永远刷不掉
|
||||
AND BINARY d.`mac_address` <> BINARY norm.`nmac`;
|
||||
|
||||
--
|
||||
-- ── ② ai_device_address_book 的两列 ────────────────────────────────────
|
||||
-- 主键是 (mac_address, target_mac),撞的是这一对,所以两列分开刷、各自判重。
|
||||
-- 一次只改一列时另一列不动,会不会撞只由这一列决定:
|
||||
-- mac 相同的行 target 必然不同(主键),target 归一成同一个值的行有 cnt 挡着。
|
||||
--
|
||||
-- 12 位以外的地址(ESP32 伪 MAC 是 32 位)正则不匹配,原样不动,和 Java 那边
|
||||
-- normalizeDeviceId 的行为一致——它同样只归一 12 位那种。mac 和 target 各自判断,
|
||||
-- 一列不合法不妨碍另一列刷(伪 MAC 那台本机的 mac 照样刷得掉)。
|
||||
|
||||
WITH norm AS (
|
||||
SELECT `mac_address`, `target_mac`, LOWER(CONCAT(SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 1, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 3, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 5, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 7, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 9, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`, ':', ''), '-', ''), '_', ''), 11, 2))) AS `nmac`
|
||||
FROM `ai_device_address_book`
|
||||
WHERE `mac_address` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
|
||||
),
|
||||
cnt AS (SELECT `nmac`, COUNT(*) AS `n` FROM norm GROUP BY `nmac`)
|
||||
UPDATE `ai_device_address_book` b
|
||||
JOIN norm ON norm.`mac_address` = b.`mac_address` AND norm.`target_mac` = b.`target_mac`
|
||||
JOIN cnt ON cnt.`nmac` = norm.`nmac`
|
||||
SET b.`mac_address` = norm.`nmac`
|
||||
WHERE cnt.`n` = 1
|
||||
AND BINARY b.`mac_address` <> BINARY norm.`nmac`;
|
||||
|
||||
WITH norm AS (
|
||||
SELECT `mac_address`, `target_mac`, LOWER(CONCAT(SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 1, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 3, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 5, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 7, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 9, 2), ':', SUBSTRING(REPLACE(REPLACE(REPLACE(`target_mac`, ':', ''), '-', ''), '_', ''), 11, 2))) AS `ntmac`
|
||||
FROM `ai_device_address_book`
|
||||
WHERE `target_mac` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
|
||||
),
|
||||
cnt AS (SELECT `ntmac`, COUNT(*) AS `n` FROM norm GROUP BY `ntmac`)
|
||||
UPDATE `ai_device_address_book` b
|
||||
JOIN norm ON norm.`mac_address` = b.`mac_address` AND norm.`target_mac` = b.`target_mac`
|
||||
JOIN cnt ON cnt.`ntmac` = norm.`ntmac`
|
||||
SET b.`target_mac` = norm.`ntmac`
|
||||
WHERE cnt.`n` = 1
|
||||
AND BINARY b.`target_mac` <> BINARY norm.`ntmac`;
|
||||
|
||||
--
|
||||
-- ── ③ 刷完之后跑这个,看有没有被跳过的重复 ─────────────────────────────
|
||||
-- 有结果说明同一台设备被填过多种写法,两行现在还是分开存的,行为和迁移前完全一样。
|
||||
-- 真要合得人来看:两行的 user_id 可能不是同一个人,谁该留下不是机器能定的,
|
||||
-- 所以这里只报不动。
|
||||
--
|
||||
-- SELECT LOWER(CONCAT(SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`,':',''),'-',''),'_',''), 1, 2), ':',
|
||||
-- SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`,':',''),'-',''),'_',''), 3, 2), ':',
|
||||
-- SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`,':',''),'-',''),'_',''), 5, 2), ':',
|
||||
-- SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`,':',''),'-',''),'_',''), 7, 2), ':',
|
||||
-- SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`,':',''),'-',''),'_',''), 9, 2), ':',
|
||||
-- SUBSTRING(REPLACE(REPLACE(REPLACE(`mac_address`,':',''),'-',''),'_',''), 11, 2))) AS `nmac`,
|
||||
-- COUNT(*) AS `c`
|
||||
-- FROM `ai_device`
|
||||
-- WHERE `mac_address` REGEXP '^([0-9A-Fa-f]{2}[-:_]?){5}[0-9A-Fa-f]{2}$'
|
||||
-- GROUP BY `nmac` HAVING `c` > 1;
|
||||
--
|
||||
-- 三段合在一个 changeset 里,也就是一个事务(Liquibase 默认 runInTransaction 为真),
|
||||
-- 任何一段报错都会整体回滚、服务起不来。所以它们不该去撞,上面的 cnt 就是为这个。
|
||||
-- 值已经是对的三段都是空操作,重跑安全。
|
||||
|
|
|
|||
|
|
@ -10,9 +10,15 @@ import static org.mockito.Mockito.mockStatic;
|
|||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.ibatis.exceptions.TooManyResultsException;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
|
@ -89,6 +95,42 @@ class DeviceMacAddressNormalizeTest {
|
|||
assertNull(service.getDeviceByMacAddress(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("库里存了两行同一个 MAC 时取第一行,不抛 TooManyResultsException")
|
||||
void duplicateRowsResolveToTheFirstOne() {
|
||||
// 迁移脚本对重复组整组跳过,库里出现同 mac 的两行是可能的:
|
||||
// 用户把同一台设备用两种写法各添加过一次,迁移前后都该读得出来
|
||||
DeviceEntity older = storedDevice("AA-BB-CC-DD-EE-FF");
|
||||
older.setId("dev-old");
|
||||
DeviceEntity newer = storedDevice("aa:bb:cc:dd:ee:ff");
|
||||
newer.setId("dev-new");
|
||||
|
||||
DeviceDao dao = mock(DeviceDao.class);
|
||||
when(dao.selectList(any())).thenReturn(List.of(older, newer));
|
||||
// selectOne 命中多行就是 MyBatis-Plus 抛的 TooManyResultsException,
|
||||
// 这里照抄真库的行为:用 selectOne 的写法改回去,用例会带着这个异常炸掉
|
||||
when(dao.selectOne(any())).thenThrow(
|
||||
new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: 2"));
|
||||
DeviceServiceImpl service = service(dao);
|
||||
|
||||
DeviceEntity found = service.getDeviceByMacAddress(CANONICAL);
|
||||
assertSame(older, found, "重复行应按 id 排完取第一条,两次读到同一台");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("迁移脚本只刷归一后不会撞车的行,撞上的整组不动")
|
||||
void migrationLeavesCollidingGroupsAlone() {
|
||||
String sql = readChangelog("202610231200.sql");
|
||||
assertTrue(sql.contains("COUNT(*) AS `n` FROM norm GROUP BY `nmac`"),
|
||||
"迁移没做重复检测");
|
||||
assertTrue(sql.contains("WHERE cnt.`n` = 1"),
|
||||
"迁移没按组跳过重复行,会把两行刷成同一个 mac_address");
|
||||
assertTrue(sql.contains("BINARY d.`mac_address` <> BINARY norm.`nmac`"),
|
||||
"ai_device 走 utf8mb4_0900_ai_ci,不加 BINARY 的话大写行永远刷不掉");
|
||||
assertTrue(sql.contains("COUNT(*) AS `n` FROM norm GROUP BY `ntmac`"),
|
||||
"target_mac 那一段漏了重复检测");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("手工添加按归一值查重、按归一值入库")
|
||||
void manualAddStoresNormalizedMac() {
|
||||
|
|
@ -155,9 +197,9 @@ class DeviceMacAddressNormalizeTest {
|
|||
/** 只在查询值等于 storedMac 时才命中,用来验证查的是哪个值 */
|
||||
private DeviceDao daoMatchingOnly(String storedMac, DeviceEntity row) {
|
||||
DeviceDao dao = mock(DeviceDao.class);
|
||||
when(dao.selectOne(any())).thenAnswer(invocation -> {
|
||||
when(dao.selectList(any())).thenAnswer(invocation -> {
|
||||
Wrapper<DeviceEntity> wrapper = invocation.getArgument(0);
|
||||
return storedMac.equals(queriedMac(wrapper)) ? row : null;
|
||||
return storedMac.equals(queriedMac(wrapper)) ? List.of(row) : List.of();
|
||||
});
|
||||
return dao;
|
||||
}
|
||||
|
|
@ -169,6 +211,16 @@ class DeviceMacAddressNormalizeTest {
|
|||
return device;
|
||||
}
|
||||
|
||||
private String readChangelog(String fileName) {
|
||||
try {
|
||||
return Files.readString(
|
||||
Path.of("src", "main", "resources", "db", "changelog", fileName),
|
||||
StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("读不到 " + fileName, e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private ArgumentCaptor<Wrapper<DeviceEntity>> wrapperCaptor() {
|
||||
return ArgumentCaptor.forClass(Wrapper.class);
|
||||
|
|
|
|||
Loading…
Reference in a new issue