@ysgroup/core 0.1.23 → 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ysgroup/core",
3
- "version": "0.1.23",
3
+ "version": "0.1.24",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -23,6 +23,6 @@
23
23
  "access": "public"
24
24
  },
25
25
  "devDependencies": {
26
- "@ysgroup/theme": "^0.2.5"
26
+ "@ysgroup/theme": "^0.2.6"
27
27
  }
28
28
  }
@@ -66,6 +66,24 @@ export async function sha256Hex(blob: Blob): Promise<string> {
66
66
  .join("");
67
67
  }
68
68
 
69
+ /** 续传记录在 localStorage 里的键前缀。 */
70
+ export const FILE_UPLOAD_RESUME_PREFIX = "ys:upload:";
71
+
72
+ /** 续传记录默认保留 24 小时,与服务端 ys_base.files 未完成上传的默认过期时间一致。 */
73
+ export const FILE_UPLOAD_RESUME_TTL_MS = 24 * 3600 * 1000;
74
+
75
+ /** 开启续传、重试时每块最多重试的次数(不含第一次)。 */
76
+ export const FILE_CHUNK_RETRIES = 3;
77
+
78
+ export interface YsUploadResumeOptions {
79
+ /** 续传事件,如 `resume_file_upload`。数据 `{ [idKey]: 上传编号, name, size }`,返回 `{ chunk_size, chunk_count, received }`。 */
80
+ event: string;
81
+ /** 区分「同一文件传给不同业务对象」的附加键,如业务对象 id。 */
82
+ key?: string;
83
+ /** 本地续传记录保留时长,默认 FILE_UPLOAD_RESUME_TTL_MS。 */
84
+ ttlMs?: number;
85
+ }
86
+
69
87
  export interface YsUploadChunkedOptions {
70
88
  /** 开始上传的事件与附加数据。实际发送 `{ name: file.name, size: file.size, ...data }`,data 里同名字段优先(如 content_type 自己传)。 */
71
89
  begin: { event: string; data?: Record<string, unknown> };
@@ -81,29 +99,72 @@ export interface YsUploadChunkedOptions {
81
99
  */
82
100
  idKey?: string;
83
101
  onProgress?: YsFileProgress;
84
- /** 中止:立即发 cancel 并抛出 signal.reason(默认 AbortError),不等正在进行的请求。 */
102
+ /** 中止(用户主动取消):立即发 cancel 并抛出 signal.reason(默认 AbortError),不等正在进行的请求;清掉续传记录。 */
85
103
  signal?: AbortSignal;
86
- /** 每块、finish 的单次超时,默认 FILE_CHUNK_TIMEOUT_MS。begin、cancel 用调用方默认超时。 */
104
+ /** 每块、finish 的单次超时,默认 FILE_CHUNK_TIMEOUT_MS。begin、cancel、续传用调用方默认超时。 */
87
105
  timeoutMs?: number;
106
+ /**
107
+ * 断点续传(服务端需 ys_base 0.1.99 起的 FileStore,块写入幂等)。开启时按「begin 事件 + 文件名 + 大小 +
108
+ * 修改时间 + key」把上传编号记在 localStorage(`ys:upload:` 前缀);同一文件再上传先调续传事件,从服务端已收到的
109
+ * 块接着发,续传失败(过期、不存在、不一致、网络)静默改走全新 begin。成功或取消后清掉记录。
110
+ * 连接断开、超时、页面关闭导致的失败不发 cancel、保留记录,下次可续传;服务端明确拒绝(带 code 的业务错误)
111
+ * 与用户中止照旧发 cancel 并清记录。不传或 false 时行为与 0.1.23 相同。
112
+ */
113
+ resume?: YsUploadResumeOptions | false;
114
+ /** 每块遇到网络中断、超时(以及服务端 408/429/502/503/504)时的重试次数。开启 resume 时默认 FILE_CHUNK_RETRIES,否则 0。 */
115
+ retries?: number;
116
+ /** 第一次重试前等待的毫秒数,之后每次翻倍。默认 500。 */
117
+ retryDelayMs?: number;
118
+ }
119
+
120
+ interface ResumeRecord {
121
+ id: string;
122
+ idKey: string;
123
+ expiresAt: number;
88
124
  }
89
125
 
90
126
  /**
91
127
  * 分块上传:begin → 按序发块 → finish(带整个文件 sha256),返回 finish 的结果。
92
- * 块大小、块数以 begin 返回的 chunk_size、chunk_count 为准(没返回时按 FILE_CHUNK_SIZE 计算,空文件 0 块)。
93
- * 任一步出错或中止:拿到上传编号后不等结果地发 cancel,再把原错误抛出。
128
+ * 块大小、块数以 begin(或续传)返回的 chunk_size、chunk_count 为准(没返回时按 FILE_CHUNK_SIZE 计算,空文件 0 块)。
129
+ * 出错:拿到上传编号后不等结果地发 cancel,再把原错误抛出;开启 resume 时网络类失败例外(保留记录可续传)。
130
+ * 进度只增不减;续传从已收到的比例开始。
94
131
  */
95
132
  export async function uploadChunked<T = unknown>(
96
133
  call: YsFileCall,
97
- file: Blob & { name?: string },
134
+ file: Blob & { name?: string; lastModified?: number },
98
135
  options: YsUploadChunkedOptions,
99
136
  ): Promise<T> {
100
- const { signal, onProgress } = options;
137
+ const { signal } = options;
101
138
  const timeoutMs = options.timeoutMs ?? FILE_CHUNK_TIMEOUT_MS;
139
+ const resume = options.resume || undefined;
140
+ const retries = Math.max(
141
+ 0,
142
+ options.retries ?? (resume ? FILE_CHUNK_RETRIES : 0),
143
+ );
144
+ const retryDelayMs = options.retryDelayMs ?? 500;
102
145
  signal?.throwIfAborted();
146
+ const name = file.name ?? "";
147
+ const resumeKey = resume
148
+ ? FILE_UPLOAD_RESUME_PREFIX +
149
+ [
150
+ options.begin.event,
151
+ name,
152
+ file.size,
153
+ file.lastModified ?? "",
154
+ resume.key ?? "",
155
+ ].join("|")
156
+ : "";
103
157
  let idKey = options.idKey ?? "";
104
158
  let id = "";
105
159
  let cancelled = false;
160
+ let reported = -1;
161
+ const report = (ratio: number) => {
162
+ if (ratio <= reported) return;
163
+ reported = ratio;
164
+ options.onProgress?.(ratio);
165
+ };
106
166
  const cancel = () => {
167
+ if (resumeKey) removeRecord(resumeKey);
107
168
  if (cancelled || !id) return;
108
169
  cancelled = true;
109
170
  // 不等结果:半截文件让服务端尽快清掉,取消失败也不影响抛出原错误。
@@ -111,52 +172,201 @@ export async function uploadChunked<T = unknown>(
111
172
  .then(() => call(options.cancelEvent, { [idKey]: id }))
112
173
  .catch(() => undefined);
113
174
  };
114
- const beginPromise = call(options.begin.event, {
115
- name: file.name ?? "",
116
- size: file.size,
117
- ...options.begin.data,
118
- }).then((result) => {
119
- const begin = (result ?? {}) as Record<string, unknown>;
120
- if (!idKey) idKey = "upload_id" in begin ? "upload_id" : "_id";
121
- id = String(begin[idKey] ?? "");
122
- // begin 回来前已经中止:补发 cancel,丢掉服务端刚建的上传。
123
- if (signal?.aborted) cancel();
124
- return begin;
125
- });
175
+
176
+ let session: Record<string, unknown> | undefined;
177
+ let start = 0;
126
178
  try {
127
- const begin = await abortable(beginPromise, signal);
128
- if (!id)
129
- throw new Error(`${options.begin.event} 没有返回上传编号 ${idKey}`);
130
- const chunkSize = positive(begin.chunk_size) ?? FILE_CHUNK_SIZE;
179
+ if (resume) {
180
+ sweepRecords();
181
+ const record = readRecord(resumeKey);
182
+ if (record) {
183
+ try {
184
+ const result = (await abortable(
185
+ call(resume.event, {
186
+ [record.idKey]: record.id,
187
+ name,
188
+ size: file.size,
189
+ }),
190
+ signal,
191
+ )) as Record<string, unknown> | undefined;
192
+ const received = nonNegative(result?.received);
193
+ const count = nonNegative(result?.chunk_count);
194
+ if (
195
+ received === undefined ||
196
+ (count !== undefined && received > count)
197
+ )
198
+ throw new Error("续传结果无效");
199
+ session = result;
200
+ start = received;
201
+ id = record.id;
202
+ idKey = record.idKey;
203
+ } catch (error) {
204
+ if (signal?.aborted) {
205
+ // 用户在续传询问时就取消了:把记录里的上传一并取消。
206
+ id = record.id;
207
+ idKey = record.idKey;
208
+ throw error;
209
+ }
210
+ // 过期、不存在、不一致或网络问题:丢掉记录,改走全新上传。
211
+ removeRecord(resumeKey);
212
+ }
213
+ }
214
+ }
215
+ if (!session) {
216
+ const beginPromise = call(options.begin.event, {
217
+ name,
218
+ size: file.size,
219
+ ...options.begin.data,
220
+ }).then((result) => {
221
+ const begin = (result ?? {}) as Record<string, unknown>;
222
+ if (!idKey) idKey = "upload_id" in begin ? "upload_id" : "_id";
223
+ id = String(begin[idKey] ?? "");
224
+ if (id && resumeKey)
225
+ writeRecord(resumeKey, {
226
+ id,
227
+ idKey,
228
+ expiresAt:
229
+ Date.now() + (resume?.ttlMs ?? FILE_UPLOAD_RESUME_TTL_MS),
230
+ });
231
+ // begin 回来前已经中止:补发 cancel,丢掉服务端刚建的上传。
232
+ if (signal?.aborted) cancel();
233
+ return begin;
234
+ });
235
+ session = await abortable(beginPromise, signal);
236
+ if (!id)
237
+ throw new Error(`${options.begin.event} 没有返回上传编号 ${idKey}`);
238
+ }
239
+ const chunkSize = positive(session.chunk_size) ?? FILE_CHUNK_SIZE;
131
240
  const count =
132
- nonNegative(begin.chunk_count) ?? Math.ceil(file.size / chunkSize);
133
- onProgress?.(0);
134
- for (let index = 0; index < count; index += 1) {
241
+ nonNegative(session.chunk_count) ?? Math.ceil(file.size / chunkSize);
242
+ report(count ? Math.min(start, count) / count : 0);
243
+ for (let index = start; index < count; index += 1) {
135
244
  const piece = file.slice(index * chunkSize, (index + 1) * chunkSize);
136
245
  const data = await abortable(blobToBase64(piece), signal);
137
- await abortable(
138
- call(
139
- options.chunkEvent,
140
- { [idKey]: id, index, size: piece.size, data },
141
- { timeoutMs },
142
- ),
246
+ await withRetry(
247
+ () =>
248
+ abortable(
249
+ call(
250
+ options.chunkEvent,
251
+ { [idKey]: id, index, size: piece.size, data },
252
+ { timeoutMs },
253
+ ),
254
+ signal,
255
+ ),
256
+ retries,
257
+ retryDelayMs,
143
258
  signal,
144
259
  );
145
- onProgress?.((index + 1) / count);
260
+ report((index + 1) / count);
146
261
  }
147
262
  const checksum = await abortable(sha256Hex(file), signal);
148
263
  const result = (await abortable(
149
264
  call(options.finishEvent, { [idKey]: id, checksum }, { timeoutMs }),
150
265
  signal,
151
266
  )) as T;
152
- if (!count) onProgress?.(1);
267
+ if (resumeKey) removeRecord(resumeKey);
268
+ report(1);
153
269
  return result;
154
270
  } catch (error) {
271
+ // 开启续传时,连接断开、超时这类失败保留记录、不发 cancel,下次同一文件从断点接着传。
272
+ if (resumeKey && !signal?.aborted && isTransient(error)) throw error;
155
273
  cancel();
156
274
  throw error;
157
275
  }
158
276
  }
159
277
 
278
+ /** 网络中断、超时、服务暂不可用:可以重试或续传。带数字 code 的错误视为服务端已明确答复。 */
279
+ function isTransient(error: unknown): boolean {
280
+ if (error instanceof YsLocalFileError) return false;
281
+ if ((error as { name?: unknown } | null)?.name === "AbortError") return false;
282
+ const code = (error as { code?: unknown } | null)?.code;
283
+ if (typeof code === "number") return RETRY_CODES.has(code);
284
+ return true;
285
+ }
286
+
287
+ const RETRY_CODES = new Set([408, 429, 502, 503, 504]);
288
+
289
+ async function withRetry<T>(
290
+ run: () => Promise<T>,
291
+ retries: number,
292
+ delayMs: number,
293
+ signal?: AbortSignal,
294
+ ): Promise<T> {
295
+ for (let attempt = 0; ; attempt += 1) {
296
+ try {
297
+ return await run();
298
+ } catch (error) {
299
+ if (attempt >= retries || signal?.aborted || !isTransient(error))
300
+ throw error;
301
+ await abortable(
302
+ new Promise((resolve) => setTimeout(resolve, delayMs * 2 ** attempt)),
303
+ signal,
304
+ );
305
+ }
306
+ }
307
+ }
308
+
309
+ function storage(): Storage | undefined {
310
+ try {
311
+ return globalThis.localStorage ?? undefined;
312
+ } catch {
313
+ return undefined;
314
+ }
315
+ }
316
+
317
+ function readRecord(key: string): ResumeRecord | undefined {
318
+ try {
319
+ const raw = storage()?.getItem(key);
320
+ if (!raw) return undefined;
321
+ const record = JSON.parse(raw) as Partial<ResumeRecord>;
322
+ if (
323
+ typeof record.id === "string" &&
324
+ record.id &&
325
+ typeof record.idKey === "string" &&
326
+ record.idKey &&
327
+ typeof record.expiresAt === "number" &&
328
+ record.expiresAt > Date.now()
329
+ )
330
+ return record as ResumeRecord;
331
+ } catch {
332
+ // 记录损坏:当作没有。
333
+ }
334
+ removeRecord(key);
335
+ return undefined;
336
+ }
337
+
338
+ function writeRecord(key: string, record: ResumeRecord): void {
339
+ try {
340
+ storage()?.setItem(key, JSON.stringify(record));
341
+ } catch {
342
+ // 存不下(隐私模式、配额满)就不续传,不影响本次上传。
343
+ }
344
+ }
345
+
346
+ function removeRecord(key: string): void {
347
+ try {
348
+ storage()?.removeItem(key);
349
+ } catch {
350
+ // 忽略
351
+ }
352
+ }
353
+
354
+ /** 顺手清掉过期的续传记录,免得 localStorage 越积越多。 */
355
+ function sweepRecords(): void {
356
+ const store = storage();
357
+ if (!store) return;
358
+ try {
359
+ const keys: string[] = [];
360
+ for (let index = 0; index < store.length; index += 1) {
361
+ const key = store.key(index);
362
+ if (key?.startsWith(FILE_UPLOAD_RESUME_PREFIX)) keys.push(key);
363
+ }
364
+ keys.forEach((key) => readRecord(key));
365
+ } catch {
366
+ // 忽略
367
+ }
368
+ }
369
+
160
370
  export interface YsReadChunkedOptions {
161
371
  onProgress?: YsFileProgress;
162
372
  signal?: AbortSignal;
package/src/index.ts CHANGED
@@ -41,8 +41,11 @@ export {
41
41
  type PasswordWrap,
42
42
  } from "./password";
43
43
  export {
44
+ FILE_CHUNK_RETRIES,
44
45
  FILE_CHUNK_SIZE,
45
46
  FILE_CHUNK_TIMEOUT_MS,
47
+ FILE_UPLOAD_RESUME_PREFIX,
48
+ FILE_UPLOAD_RESUME_TTL_MS,
46
49
  YsLocalFileError,
47
50
  base64ToBytes,
48
51
  blobToBase64,
@@ -53,6 +56,7 @@ export {
53
56
  type YsFileProgress,
54
57
  type YsReadChunkedOptions,
55
58
  type YsUploadChunkedOptions,
59
+ type YsUploadResumeOptions,
56
60
  } from "./fileTransfer";
57
61
  export {
58
62
  normalizeSearchText,