@ysgroup/core 0.1.16 → 0.1.17
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 +1 -1
- package/src/rest.ts +46 -9
- package/src/store.ts +92 -25
- package/src/ws.ts +171 -12
package/package.json
CHANGED
package/src/rest.ts
CHANGED
|
@@ -42,13 +42,42 @@ export interface RevealedCredential {
|
|
|
42
42
|
}
|
|
43
43
|
|
|
44
44
|
export class YsRest {
|
|
45
|
+
/**
|
|
46
|
+
* getToken 可以返回 Promise:传 store.freshToken 时,令牌快过期会先续期再发请求。
|
|
47
|
+
* renewToken 可选:服务端回 401 时业务尚未执行,续期一次后重试一次。
|
|
48
|
+
*/
|
|
45
49
|
constructor(
|
|
46
50
|
private baseUrl: string,
|
|
47
|
-
private getToken: () => string
|
|
51
|
+
private getToken: () => string | Promise<string>,
|
|
48
52
|
private rpcCall?: YsAdminRpcCall,
|
|
53
|
+
private renewToken?: () => Promise<void>,
|
|
49
54
|
) {}
|
|
50
55
|
|
|
51
|
-
private async
|
|
56
|
+
private async withAuthRetry<T>(
|
|
57
|
+
run: (token: string) => Promise<T>,
|
|
58
|
+
): Promise<T> {
|
|
59
|
+
try {
|
|
60
|
+
return await run(await this.getToken());
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (
|
|
63
|
+
!(error instanceof YsRestError) ||
|
|
64
|
+
error.status !== 401 ||
|
|
65
|
+
!this.renewToken
|
|
66
|
+
)
|
|
67
|
+
throw error;
|
|
68
|
+
await this.renewToken();
|
|
69
|
+
return await run(await this.getToken());
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
|
74
|
+
return this.withAuthRetry((token) =>
|
|
75
|
+
this.requestOnce<T>(token, method, path, body),
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private async requestOnce<T>(
|
|
80
|
+
token: string,
|
|
52
81
|
method: string,
|
|
53
82
|
path: string,
|
|
54
83
|
body?: unknown,
|
|
@@ -58,7 +87,7 @@ export class YsRest {
|
|
|
58
87
|
return (await this.rpcCall({
|
|
59
88
|
method,
|
|
60
89
|
path,
|
|
61
|
-
access_token:
|
|
90
|
+
access_token: token,
|
|
62
91
|
body,
|
|
63
92
|
user_agent: navigator.userAgent,
|
|
64
93
|
})) as T;
|
|
@@ -70,7 +99,7 @@ export class YsRest {
|
|
|
70
99
|
method,
|
|
71
100
|
headers: {
|
|
72
101
|
"Content-Type": "application/json",
|
|
73
|
-
Authorization: `Bearer ${
|
|
102
|
+
Authorization: `Bearer ${token}`,
|
|
74
103
|
},
|
|
75
104
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
76
105
|
});
|
|
@@ -88,13 +117,21 @@ export class YsRest {
|
|
|
88
117
|
return resp.status === 204 ? (undefined as T) : ((await resp.json()) as T);
|
|
89
118
|
}
|
|
90
119
|
|
|
91
|
-
private
|
|
120
|
+
private upload<T>(path: string, file: File): Promise<T> {
|
|
121
|
+
return this.withAuthRetry((token) => this.uploadOnce<T>(token, path, file));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private async uploadOnce<T>(
|
|
125
|
+
token: string,
|
|
126
|
+
path: string,
|
|
127
|
+
file: File,
|
|
128
|
+
): Promise<T> {
|
|
92
129
|
if (this.rpcCall) {
|
|
93
130
|
try {
|
|
94
131
|
return (await this.rpcCall({
|
|
95
132
|
method: "POST",
|
|
96
133
|
path,
|
|
97
|
-
access_token:
|
|
134
|
+
access_token: token,
|
|
98
135
|
upload: {
|
|
99
136
|
name: file.name,
|
|
100
137
|
content_type: file.type || "application/octet-stream",
|
|
@@ -110,7 +147,7 @@ export class YsRest {
|
|
|
110
147
|
form.append("upload", file);
|
|
111
148
|
const resp = await fetch(`${this.baseUrl}${path}`, {
|
|
112
149
|
method: "POST",
|
|
113
|
-
headers: { Authorization: `Bearer ${
|
|
150
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
114
151
|
body: form,
|
|
115
152
|
});
|
|
116
153
|
if (!resp.ok) {
|
|
@@ -246,7 +283,7 @@ export class YsRest {
|
|
|
246
283
|
return base64ToBlob(result.base64, result.content_type);
|
|
247
284
|
}
|
|
248
285
|
return fetch(`${this.baseUrl}/api/apps/${appId}/logo`, {
|
|
249
|
-
headers: { Authorization: `Bearer ${this.getToken()}` },
|
|
286
|
+
headers: { Authorization: `Bearer ${await this.getToken()}` },
|
|
250
287
|
}).then(async (resp) => {
|
|
251
288
|
if (!resp.ok) throw new YsRestError(resp.status, await resp.text());
|
|
252
289
|
return resp.blob();
|
|
@@ -373,7 +410,7 @@ export class YsRest {
|
|
|
373
410
|
return base64ToBlob(result.base64, result.content_type);
|
|
374
411
|
}
|
|
375
412
|
return fetch(`${this.baseUrl}/api/files/${fileId}/download`, {
|
|
376
|
-
headers: { Authorization: `Bearer ${this.getToken()}` },
|
|
413
|
+
headers: { Authorization: `Bearer ${await this.getToken()}` },
|
|
377
414
|
}).then(async (resp) => {
|
|
378
415
|
if (!resp.ok) throw new YsRestError(resp.status, await resp.text());
|
|
379
416
|
return resp.blob();
|
package/src/store.ts
CHANGED
|
@@ -21,6 +21,10 @@ const LS_USER = "ys_session_user";
|
|
|
21
21
|
*/
|
|
22
22
|
const RENEW_REJECTED = new Set([1, 2, 3, 4, 403]);
|
|
23
23
|
const RENEW_USED = 4;
|
|
24
|
+
/** 服务端在执行业务前拒绝令牌时的回执码。 */
|
|
25
|
+
const TOKEN_REJECTED = 401;
|
|
26
|
+
/** Access Token 剩余不足这么久就先续期再发请求。 */
|
|
27
|
+
const TOKEN_FRESH_MARGIN_MS = 60_000;
|
|
24
28
|
const RENEW_RETRY_MAX_MS = 30_000;
|
|
25
29
|
|
|
26
30
|
/** 读 JWT 的过期时间(毫秒)。只用来安排续期,验签由服务端做。 */
|
|
@@ -46,11 +50,15 @@ function readStoredUser(): Record<string, unknown> | null {
|
|
|
46
50
|
|
|
47
51
|
export const useYsStore = defineStore("ys", () => {
|
|
48
52
|
const storedAccess = localStorage.getItem(LS_ACCESS) ?? "";
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
53
|
+
const storedRefresh = localStorage.getItem(LS_REFRESH) ?? "";
|
|
54
|
+
// 页面重新加载(含标签页被浏览器回收后回来)时,只要还有刷新令牌和用户资料就先显示页面。
|
|
55
|
+
// Access Token 即使已过期也不要紧:业务请求经 call()/freshToken() 先等续期完成再发出。
|
|
56
|
+
// 只有 Auth 明确拒绝续期才回登录页。
|
|
57
|
+
const user = ref<Record<string, unknown> | null>(
|
|
58
|
+
storedRefresh && storedAccess ? readStoredUser() : null,
|
|
59
|
+
);
|
|
52
60
|
const accessToken = ref<string>(storedAccess);
|
|
53
|
-
const refreshToken = ref<string>(
|
|
61
|
+
const refreshToken = ref<string>(storedRefresh);
|
|
54
62
|
const connected = ref(false);
|
|
55
63
|
const appName = ref("");
|
|
56
64
|
const sessionMessage = ref("");
|
|
@@ -76,7 +84,11 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
76
84
|
ws = new YsWsClient(wsUrl);
|
|
77
85
|
ws.on("__connected", () => {
|
|
78
86
|
connected.value = true;
|
|
79
|
-
if (
|
|
87
|
+
if (
|
|
88
|
+
refreshToken.value &&
|
|
89
|
+
(renewOnConnect || !user.value || renewRetryMs > 0)
|
|
90
|
+
)
|
|
91
|
+
void renew();
|
|
80
92
|
});
|
|
81
93
|
ws.on("__disconnected", () => (connected.value = false));
|
|
82
94
|
ws.on("snapshot", (d: unknown) => applySnapshot(d as SnapshotData));
|
|
@@ -93,7 +105,12 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
93
105
|
|
|
94
106
|
/** 同一系统的多个标签页共用一份令牌:别的标签页续期或退出后,这里跟着更新。 */
|
|
95
107
|
function onStorage(event: StorageEvent) {
|
|
96
|
-
if (
|
|
108
|
+
if (
|
|
109
|
+
event.key !== LS_REFRESH &&
|
|
110
|
+
event.key !== LS_ACCESS &&
|
|
111
|
+
event.key !== null
|
|
112
|
+
)
|
|
113
|
+
return;
|
|
97
114
|
const access = localStorage.getItem(LS_ACCESS) ?? "";
|
|
98
115
|
const refresh = localStorage.getItem(LS_REFRESH) ?? "";
|
|
99
116
|
if (!refresh) {
|
|
@@ -114,7 +131,8 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
114
131
|
function adoptStoredSession(): boolean {
|
|
115
132
|
const access = localStorage.getItem(LS_ACCESS) ?? "";
|
|
116
133
|
const refresh = localStorage.getItem(LS_REFRESH) ?? "";
|
|
117
|
-
if (!access || !refresh || tokenExpiresAt(access) <= Date.now())
|
|
134
|
+
if (!access || !refresh || tokenExpiresAt(access) <= Date.now())
|
|
135
|
+
return false;
|
|
118
136
|
accessToken.value = access;
|
|
119
137
|
refreshToken.value = refresh;
|
|
120
138
|
const stored = readStoredUser();
|
|
@@ -200,17 +218,48 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
200
218
|
async function waitUntilConnected(timeoutMs = 10000): Promise<void> {
|
|
201
219
|
if (connected.value) return;
|
|
202
220
|
if (!ws) throw new Error("未连接");
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
221
|
+
if (!(await ws.waitReady(timeoutMs))) throw new Error("连接服务超时");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* 返回可用的 Access Token。快过期(60 秒内)或已过期就先等续期完成,多个请求共用同一次续期。
|
|
226
|
+
* 未登录返回空串,由服务端按未登录处理。
|
|
227
|
+
*/
|
|
228
|
+
async function freshToken(): Promise<string> {
|
|
229
|
+
if (!refreshToken.value) return accessToken.value;
|
|
230
|
+
const expiresAt = tokenExpiresAt(accessToken.value);
|
|
231
|
+
if (!expiresAt || expiresAt - Date.now() < TOKEN_FRESH_MARGIN_MS)
|
|
232
|
+
await renew();
|
|
233
|
+
return accessToken.value;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* 业务请求统一入口:自动带上新鲜的 Access Token。
|
|
238
|
+
* 服务端回「令牌无效」时业务处理尚未执行,续期一次后重试一次是安全的。
|
|
239
|
+
*/
|
|
240
|
+
async function call<T = unknown>(
|
|
241
|
+
event: string,
|
|
242
|
+
data: Record<string, unknown> = {},
|
|
243
|
+
): Promise<T> {
|
|
244
|
+
if (!ws) throw new Error("未连接");
|
|
245
|
+
const send = async () =>
|
|
246
|
+
(await ws!.call(event, {
|
|
247
|
+
...data,
|
|
248
|
+
access_token: await freshToken(),
|
|
249
|
+
})) as T;
|
|
250
|
+
try {
|
|
251
|
+
return await send();
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (
|
|
254
|
+
!(error instanceof YsRpcError) ||
|
|
255
|
+
error.code !== TOKEN_REJECTED ||
|
|
256
|
+
!refreshToken.value
|
|
257
|
+
)
|
|
258
|
+
throw error;
|
|
259
|
+
await renew();
|
|
260
|
+
if (!refreshToken.value) throw error;
|
|
261
|
+
return await send();
|
|
262
|
+
}
|
|
214
263
|
}
|
|
215
264
|
|
|
216
265
|
async function changeMyPassword(
|
|
@@ -256,21 +305,34 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
256
305
|
|
|
257
306
|
function scheduleRenew(ttlSeconds = 0) {
|
|
258
307
|
if (renewTimer) clearTimeout(renewTimer);
|
|
259
|
-
const expiresAt =
|
|
260
|
-
|
|
308
|
+
const expiresAt =
|
|
309
|
+
tokenExpiresAt(accessToken.value) || Date.now() + ttlSeconds * 1000;
|
|
310
|
+
const delay = Math.max(
|
|
311
|
+
5_000,
|
|
312
|
+
expiresAt - Date.now() - renewLeadMs(expiresAt),
|
|
313
|
+
);
|
|
261
314
|
renewDueAt = Date.now() + delay;
|
|
262
315
|
renewTimer = setTimeout(() => void renew(), delay);
|
|
263
316
|
}
|
|
264
317
|
|
|
265
318
|
function scheduleRetry() {
|
|
266
319
|
if (renewTimer) clearTimeout(renewTimer);
|
|
267
|
-
renewRetryMs = Math.min(
|
|
320
|
+
renewRetryMs = Math.min(
|
|
321
|
+
renewRetryMs ? renewRetryMs * 2 : 2_000,
|
|
322
|
+
RENEW_RETRY_MAX_MS,
|
|
323
|
+
);
|
|
268
324
|
renewDueAt = Date.now() + renewRetryMs;
|
|
269
|
-
renewTimer = setTimeout(
|
|
325
|
+
renewTimer = setTimeout(
|
|
326
|
+
() => void renew(),
|
|
327
|
+
renewRetryMs + Math.random() * 1_000,
|
|
328
|
+
);
|
|
270
329
|
}
|
|
271
330
|
|
|
272
331
|
/** 等别的标签页把轮换后的刷新令牌写进来。并发续期时只有一个标签页能用旧令牌换成功。 */
|
|
273
|
-
async function waitForOtherTab(
|
|
332
|
+
async function waitForOtherTab(
|
|
333
|
+
usedToken: string,
|
|
334
|
+
timeoutMs = 3_000,
|
|
335
|
+
): Promise<boolean> {
|
|
274
336
|
const deadline = Date.now() + timeoutMs;
|
|
275
337
|
while (Date.now() < deadline) {
|
|
276
338
|
const stored = localStorage.getItem(LS_REFRESH) ?? "";
|
|
@@ -291,13 +353,16 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
291
353
|
if (!refreshToken.value) return;
|
|
292
354
|
const stored = localStorage.getItem(LS_REFRESH) ?? "";
|
|
293
355
|
if (stored && stored !== refreshToken.value && adoptStoredSession()) return;
|
|
294
|
-
|
|
356
|
+
// 刚回到前台时连接可能正在恢复,先等一会儿再续期,不要直接放弃。
|
|
357
|
+
if (!ws || !(await ws.waitReady())) {
|
|
295
358
|
scheduleRetry();
|
|
296
359
|
return;
|
|
297
360
|
}
|
|
298
361
|
const used = refreshToken.value;
|
|
299
362
|
try {
|
|
300
|
-
const result = (await ws.call("refresh", {
|
|
363
|
+
const result = (await ws.call("refresh", {
|
|
364
|
+
refresh_token: used,
|
|
365
|
+
})) as LoginResult;
|
|
301
366
|
setSession(result);
|
|
302
367
|
} catch (error) {
|
|
303
368
|
if (!(error instanceof YsRpcError) || !RENEW_REJECTED.has(error.code)) {
|
|
@@ -355,6 +420,8 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
355
420
|
login,
|
|
356
421
|
loginByCode,
|
|
357
422
|
waitUntilConnected,
|
|
423
|
+
freshToken,
|
|
424
|
+
call,
|
|
358
425
|
changeMyPassword,
|
|
359
426
|
renew,
|
|
360
427
|
logout,
|
package/src/ws.ts
CHANGED
|
@@ -32,6 +32,14 @@ export class YsRpcError extends Error {
|
|
|
32
32
|
|
|
33
33
|
type EventHandler = (data: unknown) => void;
|
|
34
34
|
|
|
35
|
+
/** 回到前台、空闲多久没收到任何消息就探测一次。 */
|
|
36
|
+
const IDLE_PROBE_MS = 20_000;
|
|
37
|
+
/** 前台心跳:可见时每隔这么久检查一次是否需要探测。后台标签页不探测。 */
|
|
38
|
+
const HEARTBEAT_TICK_MS = 10_000;
|
|
39
|
+
/** 探测超时。超时即判定连接假死,立即重连。 */
|
|
40
|
+
const PROBE_TIMEOUT_MS = 3_000;
|
|
41
|
+
const RECONNECT_MAX_MS = 30_000;
|
|
42
|
+
|
|
35
43
|
export class YsWsClient {
|
|
36
44
|
private ws: WebSocket | null = null;
|
|
37
45
|
private seq = 0;
|
|
@@ -42,20 +50,55 @@ export class YsWsClient {
|
|
|
42
50
|
>();
|
|
43
51
|
private handlers = new Map<string, EventHandler[]>();
|
|
44
52
|
private reconnectDelay = 1000;
|
|
53
|
+
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
54
|
+
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
|
45
55
|
private stopped = false;
|
|
56
|
+
/** 收到 hello 后才算连上;断开时清除。 */
|
|
57
|
+
private ready = false;
|
|
58
|
+
private readyWaiters: (() => void)[] = [];
|
|
59
|
+
private lastMessageAt = 0;
|
|
60
|
+
private probing = false;
|
|
61
|
+
private readonly onWake = () => this.wake();
|
|
62
|
+
private readonly onPageShow = (event: PageTransitionEvent) => {
|
|
63
|
+
if (event.persisted) this.wake();
|
|
64
|
+
};
|
|
46
65
|
|
|
47
66
|
constructor(
|
|
48
67
|
private url: string,
|
|
49
68
|
private callTimeout = 10_000,
|
|
50
69
|
) {}
|
|
51
70
|
|
|
71
|
+
get connected(): boolean {
|
|
72
|
+
return this.ready;
|
|
73
|
+
}
|
|
74
|
+
|
|
52
75
|
start(): void {
|
|
53
76
|
this.stopped = false;
|
|
54
77
|
this.connect();
|
|
78
|
+
if (typeof window !== "undefined") {
|
|
79
|
+
document.addEventListener("visibilitychange", this.onWake);
|
|
80
|
+
window.addEventListener("focus", this.onWake);
|
|
81
|
+
window.addEventListener("online", this.onWake);
|
|
82
|
+
window.addEventListener("pageshow", this.onPageShow);
|
|
83
|
+
this.heartbeatTimer = setInterval(
|
|
84
|
+
() => this.heartbeat(),
|
|
85
|
+
HEARTBEAT_TICK_MS,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
55
88
|
}
|
|
56
89
|
|
|
57
90
|
stop(): void {
|
|
58
91
|
this.stopped = true;
|
|
92
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
93
|
+
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
94
|
+
this.reconnectTimer = null;
|
|
95
|
+
this.heartbeatTimer = null;
|
|
96
|
+
if (typeof window !== "undefined") {
|
|
97
|
+
document.removeEventListener("visibilitychange", this.onWake);
|
|
98
|
+
window.removeEventListener("focus", this.onWake);
|
|
99
|
+
window.removeEventListener("online", this.onWake);
|
|
100
|
+
window.removeEventListener("pageshow", this.onPageShow);
|
|
101
|
+
}
|
|
59
102
|
this.ws?.close();
|
|
60
103
|
}
|
|
61
104
|
|
|
@@ -71,17 +114,45 @@ export class YsWsClient {
|
|
|
71
114
|
};
|
|
72
115
|
}
|
|
73
116
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
117
|
+
/** 等连接就绪,最多 timeoutMs。已就绪立即返回 true。 */
|
|
118
|
+
waitReady(timeoutMs = this.callTimeout): Promise<boolean> {
|
|
119
|
+
if (this.ready) return Promise.resolve(true);
|
|
120
|
+
this.wake();
|
|
121
|
+
return new Promise((resolve) => {
|
|
122
|
+
const done = () => {
|
|
123
|
+
clearTimeout(timer);
|
|
124
|
+
resolve(true);
|
|
125
|
+
};
|
|
126
|
+
const timer = setTimeout(() => {
|
|
127
|
+
this.readyWaiters = this.readyWaiters.filter((item) => item !== done);
|
|
128
|
+
resolve(false);
|
|
129
|
+
}, timeoutMs);
|
|
130
|
+
this.readyWaiters.push(done);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 断线时发起的请求先等连接恢复(最多一个调用超时)再发出:它还没发出去,补发不会重复执行。
|
|
136
|
+
* 已经发出、途中断线的请求结果未知,仍然报错,避免写操作被执行两次。
|
|
137
|
+
*/
|
|
138
|
+
async call(
|
|
139
|
+
event: string,
|
|
140
|
+
data: unknown = {},
|
|
141
|
+
timeoutMs = this.callTimeout,
|
|
142
|
+
): Promise<unknown> {
|
|
143
|
+
if (!this.ready && !(await this.waitReady(timeoutMs))) {
|
|
144
|
+
throw new Error("not connected");
|
|
77
145
|
}
|
|
146
|
+
const ws = this.ws;
|
|
147
|
+
if (!ws || ws.readyState !== WebSocket.OPEN)
|
|
148
|
+
throw new Error("not connected");
|
|
78
149
|
const id = `${this.connectionId || "c0"}:${++this.seq}`;
|
|
79
|
-
|
|
150
|
+
ws.send(JSON.stringify({ event, id, ts: Date.now() / 1000, data }));
|
|
80
151
|
return new Promise((resolve, reject) => {
|
|
81
152
|
const timer = setTimeout(() => {
|
|
82
153
|
this.pending.delete(id);
|
|
83
154
|
reject(new Error(`call ${event} timed out`));
|
|
84
|
-
},
|
|
155
|
+
}, timeoutMs);
|
|
85
156
|
this.pending.set(id, {
|
|
86
157
|
resolve: (v) => {
|
|
87
158
|
clearTimeout(timer);
|
|
@@ -99,6 +170,85 @@ export class YsWsClient {
|
|
|
99
170
|
this.ws?.send(JSON.stringify({ event, ts: Date.now() / 1000, data }));
|
|
100
171
|
}
|
|
101
172
|
|
|
173
|
+
/**
|
|
174
|
+
* 回到前台、窗口获得焦点、网络恢复时调用:断开就跳过退避立即重连;
|
|
175
|
+
* 看似连着但很久没有消息,就探测一次,假死立即重连。
|
|
176
|
+
*/
|
|
177
|
+
wake(): void {
|
|
178
|
+
if (this.stopped) return;
|
|
179
|
+
if (
|
|
180
|
+
typeof document !== "undefined" &&
|
|
181
|
+
document.visibilityState === "hidden"
|
|
182
|
+
)
|
|
183
|
+
return;
|
|
184
|
+
const state = this.ws?.readyState;
|
|
185
|
+
if (state === WebSocket.CONNECTING) return;
|
|
186
|
+
if (!this.ready || state !== WebSocket.OPEN) {
|
|
187
|
+
if (this.reconnectTimer) {
|
|
188
|
+
clearTimeout(this.reconnectTimer);
|
|
189
|
+
this.reconnectTimer = null;
|
|
190
|
+
this.reconnectDelay = 1000;
|
|
191
|
+
this.connect();
|
|
192
|
+
}
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (Date.now() - this.lastMessageAt > IDLE_PROBE_MS) void this.probe();
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private heartbeat(): void {
|
|
199
|
+
if (
|
|
200
|
+
typeof document !== "undefined" &&
|
|
201
|
+
document.visibilityState !== "visible"
|
|
202
|
+
)
|
|
203
|
+
return;
|
|
204
|
+
if (this.ready && Date.now() - this.lastMessageAt > IDLE_PROBE_MS)
|
|
205
|
+
void this.probe();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 任何回复(包括「未知事件」)都说明连接活着;只有超时或断线才算假死。 */
|
|
209
|
+
private async probe(): Promise<void> {
|
|
210
|
+
if (this.probing) return;
|
|
211
|
+
this.probing = true;
|
|
212
|
+
const socket = this.ws;
|
|
213
|
+
try {
|
|
214
|
+
await this.call("ping", {}, PROBE_TIMEOUT_MS);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (!(error instanceof YsRpcError) && socket === this.ws)
|
|
217
|
+
this.reconnectNow();
|
|
218
|
+
} finally {
|
|
219
|
+
this.probing = false;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 丢弃假死连接并立刻新建,不等浏览器慢慢关闭旧连接。 */
|
|
224
|
+
private reconnectNow(): void {
|
|
225
|
+
const old = this.ws;
|
|
226
|
+
if (old) {
|
|
227
|
+
old.onopen = null;
|
|
228
|
+
old.onmessage = null;
|
|
229
|
+
old.onclose = null;
|
|
230
|
+
try {
|
|
231
|
+
old.close();
|
|
232
|
+
} catch {
|
|
233
|
+
// 旧连接已不可用,忽略。
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
this.handleClosed();
|
|
237
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
238
|
+
this.reconnectTimer = null;
|
|
239
|
+
this.reconnectDelay = 1000;
|
|
240
|
+
if (!this.stopped) this.connect();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
private handleClosed(): void {
|
|
244
|
+
for (const p of this.pending.values())
|
|
245
|
+
p.reject(new Error("connection lost"));
|
|
246
|
+
this.pending.clear();
|
|
247
|
+
const wasReady = this.ready;
|
|
248
|
+
this.ready = false;
|
|
249
|
+
if (wasReady || this.ws) this.emit("__disconnected", null);
|
|
250
|
+
}
|
|
251
|
+
|
|
102
252
|
private connect(): void {
|
|
103
253
|
const ws = new WebSocket(this.url);
|
|
104
254
|
this.ws = ws;
|
|
@@ -107,21 +257,26 @@ export class YsWsClient {
|
|
|
107
257
|
};
|
|
108
258
|
ws.onmessage = (e) => this.onMessage(e);
|
|
109
259
|
ws.onclose = () => {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
this.pending.clear();
|
|
113
|
-
this.emit("__disconnected", null);
|
|
260
|
+
if (ws !== this.ws) return;
|
|
261
|
+
this.handleClosed();
|
|
114
262
|
if (!this.stopped) {
|
|
115
|
-
setTimeout(
|
|
116
|
-
() =>
|
|
263
|
+
this.reconnectTimer = setTimeout(
|
|
264
|
+
() => {
|
|
265
|
+
this.reconnectTimer = null;
|
|
266
|
+
this.connect();
|
|
267
|
+
},
|
|
117
268
|
this.reconnectDelay + Math.random() * 1000,
|
|
118
269
|
);
|
|
119
|
-
this.reconnectDelay = Math.min(
|
|
270
|
+
this.reconnectDelay = Math.min(
|
|
271
|
+
this.reconnectDelay * 2,
|
|
272
|
+
RECONNECT_MAX_MS,
|
|
273
|
+
);
|
|
120
274
|
}
|
|
121
275
|
};
|
|
122
276
|
}
|
|
123
277
|
|
|
124
278
|
private onMessage(e: MessageEvent): void {
|
|
279
|
+
this.lastMessageAt = Date.now();
|
|
125
280
|
let msg: Envelope;
|
|
126
281
|
try {
|
|
127
282
|
msg = JSON.parse(e.data as string);
|
|
@@ -149,6 +304,10 @@ export class YsWsClient {
|
|
|
149
304
|
(msg.data as { connection_id?: string })?.connection_id ?? "",
|
|
150
305
|
);
|
|
151
306
|
applyPasswordWrap(msg.data);
|
|
307
|
+
this.ready = true;
|
|
308
|
+
const waiters = this.readyWaiters;
|
|
309
|
+
this.readyWaiters = [];
|
|
310
|
+
for (const resolve of waiters) resolve();
|
|
152
311
|
this.emit("__connected", msg.data);
|
|
153
312
|
}
|
|
154
313
|
if (msg.event === "password_wrap") applyPasswordWrap(msg.data);
|