并行开发前的清场:白名单、读流模块、流量格式化

任务书承诺这些在分发前已存在。/traffic /logs 补进读白名单(在流式清单
里却不在读白名单里,仪表盘和请求页一开工就 403),PUT /providers/rules
补进写白名单(规则页的立刻更新)。web/stream.ts 把分块流缝成完整的行,
分块边界和行边界无关是它存在的全部理由;shared/format.ts 是连接页和
仪表盘共用的流量数字格式化。
This commit is contained in:
2026-08-11 18:02:21 +08:00
parent d028e63a74
commit 6c8a1c4e0e
5 changed files with 142 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'bun:test'
import { formatBytes } from './format.ts'
describe('流量数字', () => {
it('零和不满 1KB 的按字节显示,不带小数', () => {
expect(formatBytes(0)).toBe('0 B')
expect(formatBytes(512)).toBe('512 B')
expect(formatBytes(1023)).toBe('1023 B')
})
it('1024 的边界正好换档', () => {
expect(formatBytes(1024)).toBe('1 KB')
expect(formatBytes(1024 * 1024)).toBe('1 MB')
})
it('不满 100 保留一位小数,够 100 取整', () => {
expect(formatBytes(23.4 * 1024 * 1024)).toBe('23.4 MB')
expect(formatBytes(234.7 * 1024 * 1024)).toBe('235 MB')
})
it('超大数停在 TB 档', () => {
expect(formatBytes(5 * 1024 ** 4)).toBe('5 TB')
expect(formatBytes(5000 * 1024 ** 4)).toBe('5000 TB')
})
it('脏输入不炸', () => {
expect(formatBytes(-1)).toBe('0 B')
expect(formatBytes(Number.NaN)).toBe('0 B')
})
})
+20
View File
@@ -0,0 +1,20 @@
/**
* 流量数字显示成人读的样子。连接页和仪表盘共用。
*
* 1024 进制。B 一档不带小数;其余不满 100 的保留一位小数,够 100 的取整——
* 「23.4 MB」有信息量,「234.7 MB」的小数就只是噪音了。
*/
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const
export function formatBytes(bytes: number): string {
if (!Number.isFinite(bytes) || bytes < 0) return '0 B'
let value = bytes
let unit = 0
while (value >= 1024 && unit < UNITS.length - 1) {
value /= 1024
unit += 1
}
const digits = unit === 0 || value >= 100 ? 0 : 1
// Number() 去掉无意义的尾零:1.0 KB → 1 KB
return `${String(Number(value.toFixed(digits)))} ${UNITS[unit]}`
}