274 lines
7.8 KiB
TypeScript
274 lines
7.8 KiB
TypeScript
/**
|
||
* S3存储桶速度测试脚本(独立版本)
|
||
* 直接使用S3客户端,不依赖HTTP API
|
||
*/
|
||
|
||
import { S3Client, PutObjectCommand, ListObjectsV2Command, DeleteObjectCommand, ListObjectsV2CommandOutput } from '@aws-sdk/client-s3'
|
||
import { randomBytes } from 'crypto'
|
||
|
||
const S3_ENDPOINT = process.env.S3_ENDPOINT || ''
|
||
const S3_BUCKET = process.env.S3_BUCKET || ''
|
||
const S3_PUBLIC_DOMAIN = process.env.S3_PUBLIC_DOMAIN || ''
|
||
const S3_ACCESS_KEY_ID = process.env.S3_ACCESS_KEY_ID || ''
|
||
const S3_SECRET_ACCESS_KEY = process.env.S3_SECRET_ACCESS_KEY || ''
|
||
|
||
if (!S3_ENDPOINT || !S3_BUCKET || !S3_ACCESS_KEY_ID || !S3_SECRET_ACCESS_KEY) {
|
||
console.error('❌ 缺少必要的环境变量')
|
||
console.error('需要: S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY')
|
||
process.exit(1)
|
||
}
|
||
|
||
console.log('='.repeat(60))
|
||
console.log('S3存储桶速度测试(独立版本)')
|
||
console.log('='.repeat(60))
|
||
console.log(`S3端点: ${S3_ENDPOINT}`)
|
||
console.log(`存储桶: ${S3_BUCKET}`)
|
||
console.log(`公网域名: ${S3_PUBLIC_DOMAIN}`)
|
||
console.log('='.repeat(60))
|
||
console.log('')
|
||
|
||
// 创建S3客户端
|
||
const s3Client = new S3Client({
|
||
endpoint: S3_ENDPOINT,
|
||
region: process.env.S3_REGION || 'us-east-1',
|
||
credentials: {
|
||
accessKeyId: S3_ACCESS_KEY_ID,
|
||
secretAccessKey: S3_SECRET_ACCESS_KEY,
|
||
},
|
||
forcePathStyle: true,
|
||
requestHandler: {
|
||
requestTimeout: 60000,
|
||
connectionTimeout: 10000,
|
||
},
|
||
})
|
||
|
||
// 计算统计信息
|
||
function calculateStats(durations: number[]) {
|
||
if (durations.length === 0) {
|
||
return { min: 0, max: 0, avg: 0, p50: 0, p90: 0, p95: 0, p99: 0 }
|
||
}
|
||
const sorted = [...durations].sort((a, b) => a - b)
|
||
return {
|
||
min: sorted[0],
|
||
max: sorted[sorted.length - 1],
|
||
avg: durations.reduce((a, b) => a + b, 0) / durations.length,
|
||
p50: sorted[Math.floor(sorted.length * 0.5)],
|
||
p90: sorted[Math.floor(sorted.length * 0.9)],
|
||
p95: sorted[Math.floor(sorted.length * 0.95)],
|
||
p99: sorted[Math.floor(sorted.length * 0.99)],
|
||
}
|
||
}
|
||
|
||
// 测试上传速度
|
||
async function testUploadSpeed(sizeKB: number): Promise<{ duration: number; speed: number; success: boolean; key?: string }> {
|
||
const key = `speed-test-${Date.now()}-${Math.random().toString(36).substring(7)}.bin`
|
||
const testData = randomBytes(sizeKB * 1024)
|
||
|
||
const startTime = Date.now()
|
||
try {
|
||
const command = new PutObjectCommand({
|
||
Bucket: S3_BUCKET,
|
||
Key: key,
|
||
Body: testData,
|
||
ContentType: 'application/octet-stream',
|
||
})
|
||
await s3Client.send(command)
|
||
const duration = Date.now() - startTime
|
||
const speed = (sizeKB / duration) * 1000 // KB/s
|
||
return { duration, speed, success: true, key }
|
||
} catch (error: any) {
|
||
const duration = Date.now() - startTime
|
||
return { duration, speed: 0, success: false, key }
|
||
}
|
||
}
|
||
|
||
// 并发上传测试
|
||
async function testConcurrentUploads(concurrency: number, sizeKB: number, count: number) {
|
||
const durations: number[] = []
|
||
const speeds: number[] = []
|
||
let success = 0
|
||
let failed = 0
|
||
const keys: string[] = []
|
||
|
||
const startTime = Date.now()
|
||
|
||
for (let i = 0; i < count; i += concurrency) {
|
||
const batch = []
|
||
for (let j = 0; j < concurrency && i + j < count; j++) {
|
||
batch.push(testUploadSpeed(sizeKB))
|
||
}
|
||
|
||
const results = await Promise.allSettled(batch)
|
||
|
||
for (const result of results) {
|
||
if (result.status === 'fulfilled') {
|
||
const r = result.value
|
||
if (r.success) {
|
||
durations.push(r.duration)
|
||
speeds.push(r.speed)
|
||
success++
|
||
if (r.key) keys.push(r.key)
|
||
} else {
|
||
failed++
|
||
}
|
||
} else {
|
||
failed++
|
||
}
|
||
}
|
||
|
||
process.stdout.write(`\r进度: ${Math.min(i + concurrency, count)}/${count} (成功: ${success}, 失败: ${failed})`)
|
||
}
|
||
|
||
console.log('')
|
||
|
||
const totalTime = Date.now() - startTime
|
||
const totalSizeMB = (success * sizeKB) / 1024
|
||
const throughput = totalTime > 0 ? (totalSizeMB / totalTime) * 1000 : 0
|
||
|
||
// 清理测试文件
|
||
if (keys.length > 0) {
|
||
console.log(`清理 ${keys.length} 个测试文件...`)
|
||
await Promise.allSettled(
|
||
keys.map(key =>
|
||
s3Client.send(
|
||
new DeleteObjectCommand({
|
||
Bucket: S3_BUCKET,
|
||
Key: key,
|
||
})
|
||
)
|
||
)
|
||
)
|
||
}
|
||
|
||
return {
|
||
total: count,
|
||
success,
|
||
failed,
|
||
durations,
|
||
speeds,
|
||
stats: calculateStats(durations),
|
||
throughput,
|
||
}
|
||
}
|
||
|
||
// 清理所有测试文件
|
||
async function cleanupAllTestFiles() {
|
||
let deleted = 0
|
||
let failed = 0
|
||
let continuationToken: string | undefined = undefined
|
||
|
||
try {
|
||
do {
|
||
const listCommand: ListObjectsV2Command = new ListObjectsV2Command({
|
||
Bucket: S3_BUCKET,
|
||
Prefix: 'speed-test-',
|
||
ContinuationToken: continuationToken,
|
||
MaxKeys: 1000,
|
||
})
|
||
|
||
const listResponse = await s3Client.send(listCommand) as ListObjectsV2CommandOutput
|
||
|
||
if (listResponse.Contents && listResponse.Contents.length > 0) {
|
||
const deletePromises = listResponse.Contents.map((file) => {
|
||
if (file.Key) {
|
||
return s3Client.send(
|
||
new DeleteObjectCommand({
|
||
Bucket: S3_BUCKET,
|
||
Key: file.Key,
|
||
})
|
||
).then(() => {
|
||
deleted++
|
||
}).catch(() => {
|
||
failed++
|
||
})
|
||
}
|
||
return Promise.resolve()
|
||
})
|
||
|
||
await Promise.allSettled(deletePromises)
|
||
}
|
||
|
||
continuationToken = listResponse.NextContinuationToken
|
||
} while (continuationToken)
|
||
} catch (error) {
|
||
console.warn('清理错误:', error)
|
||
}
|
||
|
||
return { deleted, failed }
|
||
}
|
||
|
||
// 主测试函数
|
||
async function runTests() {
|
||
console.log('开始测试...\n')
|
||
|
||
// 1. 单文件上传测试
|
||
console.log('1. 单文件上传测试(不同大小)...')
|
||
const uploadSizes = [10, 100, 1024] // 10KB, 100KB, 1MB
|
||
const uploadResults: any = {}
|
||
|
||
for (const sizeKB of uploadSizes) {
|
||
const test = await testUploadSpeed(sizeKB)
|
||
uploadResults[`${sizeKB}KB`] = {
|
||
sizeKB,
|
||
duration: test.duration,
|
||
speedKBps: test.speed,
|
||
speedMBps: test.speed / 1024,
|
||
success: test.success,
|
||
}
|
||
|
||
// 清理
|
||
if (test.key) {
|
||
await s3Client.send(
|
||
new DeleteObjectCommand({
|
||
Bucket: S3_BUCKET,
|
||
Key: test.key,
|
||
})
|
||
).catch(() => {})
|
||
}
|
||
|
||
console.log(` ${test.success ? '✓' : '✗'} ${sizeKB}KB: ${(test.speed / 1024).toFixed(2)} MB/s (${test.duration}ms)`)
|
||
}
|
||
console.log('')
|
||
|
||
// 2. 并发上传测试
|
||
console.log('2. 并发上传测试...')
|
||
const concurrentTests = [
|
||
{ size: 100, concurrency: 10, count: 50 },
|
||
{ size: 100, concurrency: 20, count: 100 },
|
||
{ size: 100, concurrency: 50, count: 200 },
|
||
]
|
||
|
||
for (const config of concurrentTests) {
|
||
console.log(`\n测试: ${config.size}KB, ${config.concurrency}并发, ${config.count}次`)
|
||
const test = await testConcurrentUploads(config.concurrency, config.size, config.count)
|
||
const successRate = ((test.success / test.total) * 100).toFixed(1)
|
||
console.log(` 成功率: ${successRate}% (${test.success}/${test.total})`)
|
||
console.log(` 吞吐量: ${test.throughput.toFixed(2)} MB/s`)
|
||
console.log(` 延迟: min=${test.stats.min}ms, avg=${test.stats.avg.toFixed(1)}ms, p95=${test.stats.p95}ms, p99=${test.stats.p99}ms`)
|
||
}
|
||
console.log('')
|
||
|
||
// 3. 最终清理
|
||
console.log('3. 清理所有测试文件...')
|
||
const cleanupResult = await cleanupAllTestFiles()
|
||
console.log(` 已删除: ${cleanupResult.deleted} 个文件`)
|
||
if (cleanupResult.failed > 0) {
|
||
console.log(` 失败: ${cleanupResult.failed} 个文件`)
|
||
}
|
||
console.log('')
|
||
|
||
console.log('='.repeat(60))
|
||
console.log('测试完成!')
|
||
console.log('='.repeat(60))
|
||
}
|
||
|
||
// 运行测试
|
||
runTests()
|
||
.then(() => {
|
||
process.exit(0)
|
||
})
|
||
.catch((error) => {
|
||
console.error('测试失败:', error)
|
||
process.exit(1)
|
||
})
|