-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoss.ts
More file actions
155 lines (127 loc) · 5.5 KB
/
oss.ts
File metadata and controls
155 lines (127 loc) · 5.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import OSS from 'ali-oss';
import { StorageConfig, StorageService } from '../types/index.js';
export class OssStorageService implements StorageService {
private client: OSS;
private downloadLinkExpiry: number;
private timeout: number;
constructor(config: StorageConfig) {
// 从环境变量获取超时配置,默认300秒(5分钟)
const envTimeout = process.env.OSS_TIMEOUT ? parseInt(process.env.OSS_TIMEOUT) : 300;
this.timeout = (config.timeout || envTimeout) * 1000; // 转换为毫秒
console.log(`[OSS] 初始化OSS客户端,超时配置: ${this.timeout}ms (${this.timeout/1000}秒)`);
console.log(`[OSS] 环境变量OSS_TIMEOUT: ${process.env.OSS_TIMEOUT || '未设置'}`);
console.log(`[OSS] 配置超时: ${config.timeout || '未设置'}秒`);
console.log(`[OSS] 最终使用超时: ${this.timeout/1000}秒`);
this.client = new OSS({
region: config.region,
accessKeyId: config.accessKeyId,
accessKeySecret: config.accessKeySecret,
bucket: config.bucket,
secure: config.secure,
timeout: this.timeout, // 设置全局超时
});
// 默认1小时过期
this.downloadLinkExpiry = 3600;
}
async uploadFile(content: Buffer, filename: string): Promise<string> {
try {
console.log(`[OSS] 开始上传文件: ${filename}, 大小: ${content.length} bytes, 超时: ${this.timeout}ms`);
const startTime = Date.now();
const result = await this.client.put(filename, content, {
timeout: this.timeout, // 为单个操作设置超时
});
const duration = Date.now() - startTime;
console.log(`[OSS] 文件上传成功: ${filename}, 耗时: ${duration}ms`);
return result.name;
} catch (error) {
console.error(`[OSS] 文件上传失败: ${filename}`, error);
if (error instanceof Error && (error.name === 'ConnectionTimeoutError' || (error as any).code === 'ConnectionTimeout')) {
throw new Error(`文件上传超时(${this.timeout/1000}秒),请稍后重试`);
}
throw new Error('文件上传失败');
}
}
async generateTempUrl(filename: string): Promise<string> {
try {
console.log(`[OSS] 生成临时下载链接: ${filename}, 过期时间: ${this.downloadLinkExpiry}秒`);
const startTime = Date.now();
const url = await this.client.signatureUrl(filename, {
expires: this.downloadLinkExpiry, // signatureUrl的expires参数是秒数,不是毫秒
});
const duration = Date.now() - startTime;
console.log(`[OSS] 临时链接生成成功: ${filename}, 耗时: ${duration}ms`);
return url;
} catch (error) {
console.error(`[OSS] 生成临时下载链接失败: ${filename}`, error);
throw new Error('生成临时下载链接失败');
}
}
async deleteFile(filename: string): Promise<void> {
try {
console.log(`[OSS] 删除文件: ${filename}`);
const startTime = Date.now();
await this.client.delete(filename, {
timeout: this.timeout,
});
const duration = Date.now() - startTime;
console.log(`[OSS] 文件删除成功: ${filename}, 耗时: ${duration}ms`);
} catch (error) {
console.error(`[OSS] 文件删除失败: ${filename}`, error);
throw new Error('文件删除失败');
}
}
async listExpiredFiles(): Promise<string[]> {
try {
console.log(`[OSS] 开始列出过期文件, 超时: ${this.timeout}ms`);
const startTime = Date.now();
const now = Date.now();
const expiredFiles: string[] = [];
const maxKeys = 1000;
let marker: string | null = null;
do {
const result = await this.client.list({
'max-keys': maxKeys,
marker: marker || undefined,
prefix: '',
}, {
timeout: this.timeout // 使用配置的超时时间
});
for (const object of result.objects || []) {
const fileAge = now - new Date(object.lastModified).getTime();
// 如果文件超过2小时
if (fileAge > 7200000) {
expiredFiles.push(object.name);
}
}
marker = result.nextMarker;
} while (marker);
const duration = Date.now() - startTime;
console.log(`[OSS] 列出过期文件完成, 找到 ${expiredFiles.length} 个过期文件, 耗时: ${duration}ms`);
return expiredFiles;
} catch (error) {
console.error('[OSS] 列出过期文件失败:', error);
return [];
}
}
async getFileContent(filename: string): Promise<Buffer> {
try {
console.log(`[OSS] 获取文件内容: ${filename}, 超时: ${this.timeout}ms`);
const startTime = Date.now();
const result = await this.client.get(filename, {
timeout: this.timeout,
});
if (!result.content) {
throw new Error('No content received');
}
const duration = Date.now() - startTime;
console.log(`[OSS] 文件内容获取成功: ${filename}, 大小: ${result.content.length} bytes, 耗时: ${duration}ms`);
return result.content;
} catch (error) {
console.error(`[OSS] 获取文件内容失败: ${filename}`, error);
if (error instanceof Error && (error.name === 'ConnectionTimeoutError' || (error as any).code === 'ConnectionTimeout')) {
throw new Error(`获取文件内容超时(${this.timeout/1000}秒),请稍后重试`);
}
throw new Error('获取文件内容失败');
}
}
}