@ysgroup/core 0.1.15 → 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 +218 -32
- 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
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { defineStore } from "pinia";
|
|
3
3
|
import { ref, computed } from "vue";
|
|
4
4
|
import { sealLoginPassword } from "./password";
|
|
5
|
-
import { YsWsClient } from "./ws";
|
|
5
|
+
import { YsRpcError, YsWsClient } from "./ws";
|
|
6
6
|
|
|
7
7
|
interface LoginResult {
|
|
8
8
|
user?: Record<string, unknown>;
|
|
@@ -13,11 +13,52 @@ interface LoginResult {
|
|
|
13
13
|
|
|
14
14
|
const LS_ACCESS = "ys_access_token";
|
|
15
15
|
const LS_REFRESH = "ys_refresh_token";
|
|
16
|
+
const LS_USER = "ys_session_user";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Auth 明确拒绝续期的回执码:刷新令牌无效或过期、用户已停用、应用授权已撤销、刷新令牌已被使用、禁止登录。
|
|
20
|
+
* 只有这些才清会话。断线、超时、503(Auth 正在重连)、500 都是暂时的,保留会话继续重试。
|
|
21
|
+
*/
|
|
22
|
+
const RENEW_REJECTED = new Set([1, 2, 3, 4, 403]);
|
|
23
|
+
const RENEW_USED = 4;
|
|
24
|
+
/** 服务端在执行业务前拒绝令牌时的回执码。 */
|
|
25
|
+
const TOKEN_REJECTED = 401;
|
|
26
|
+
/** Access Token 剩余不足这么久就先续期再发请求。 */
|
|
27
|
+
const TOKEN_FRESH_MARGIN_MS = 60_000;
|
|
28
|
+
const RENEW_RETRY_MAX_MS = 30_000;
|
|
29
|
+
|
|
30
|
+
/** 读 JWT 的过期时间(毫秒)。只用来安排续期,验签由服务端做。 */
|
|
31
|
+
function tokenExpiresAt(token: string): number {
|
|
32
|
+
try {
|
|
33
|
+
const part = token.split(".")[1] ?? "";
|
|
34
|
+
const json = atob(part.replace(/-/g, "+").replace(/_/g, "/"));
|
|
35
|
+
const exp = Number((JSON.parse(json) as { exp?: number }).exp ?? 0);
|
|
36
|
+
return exp > 0 ? exp * 1000 : 0;
|
|
37
|
+
} catch {
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function readStoredUser(): Record<string, unknown> | null {
|
|
43
|
+
try {
|
|
44
|
+
const raw = localStorage.getItem(LS_USER);
|
|
45
|
+
return raw ? (JSON.parse(raw) as Record<string, unknown>) : null;
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
16
50
|
|
|
17
51
|
export const useYsStore = defineStore("ys", () => {
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
|
|
52
|
+
const storedAccess = localStorage.getItem(LS_ACCESS) ?? "";
|
|
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
|
+
);
|
|
60
|
+
const accessToken = ref<string>(storedAccess);
|
|
61
|
+
const refreshToken = ref<string>(storedRefresh);
|
|
21
62
|
const connected = ref(false);
|
|
22
63
|
const appName = ref("");
|
|
23
64
|
const sessionMessage = ref("");
|
|
@@ -26,6 +67,11 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
26
67
|
|
|
27
68
|
let ws: YsWsClient | null = null;
|
|
28
69
|
let renewTimer: ReturnType<typeof setTimeout> | null = null;
|
|
70
|
+
let renewing: Promise<void> | null = null;
|
|
71
|
+
let renewRetryMs = 0;
|
|
72
|
+
let renewDueAt = 0;
|
|
73
|
+
// 页面加载后首次连上时换一次令牌,顺带刷新用户资料;之后按令牌寿命定时续期。
|
|
74
|
+
let renewOnConnect = !!refreshToken.value;
|
|
29
75
|
|
|
30
76
|
const isLoggedIn = computed(() => !!accessToken.value && !!user.value);
|
|
31
77
|
|
|
@@ -38,7 +84,11 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
38
84
|
ws = new YsWsClient(wsUrl);
|
|
39
85
|
ws.on("__connected", () => {
|
|
40
86
|
connected.value = true;
|
|
41
|
-
if (
|
|
87
|
+
if (
|
|
88
|
+
refreshToken.value &&
|
|
89
|
+
(renewOnConnect || !user.value || renewRetryMs > 0)
|
|
90
|
+
)
|
|
91
|
+
void renew();
|
|
42
92
|
});
|
|
43
93
|
ws.on("__disconnected", () => (connected.value = false));
|
|
44
94
|
ws.on("snapshot", (d: unknown) => applySnapshot(d as SnapshotData));
|
|
@@ -48,6 +98,48 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
48
98
|
);
|
|
49
99
|
ws.on("resync", () => {}); // 前端订阅本子系统后端,resync 由后端 SDK 处理
|
|
50
100
|
ws.start();
|
|
101
|
+
window.addEventListener("storage", onStorage);
|
|
102
|
+
document.addEventListener("visibilitychange", onVisible);
|
|
103
|
+
if (user.value && accessToken.value) scheduleRenew();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 同一系统的多个标签页共用一份令牌:别的标签页续期或退出后,这里跟着更新。 */
|
|
107
|
+
function onStorage(event: StorageEvent) {
|
|
108
|
+
if (
|
|
109
|
+
event.key !== LS_REFRESH &&
|
|
110
|
+
event.key !== LS_ACCESS &&
|
|
111
|
+
event.key !== null
|
|
112
|
+
)
|
|
113
|
+
return;
|
|
114
|
+
const access = localStorage.getItem(LS_ACCESS) ?? "";
|
|
115
|
+
const refresh = localStorage.getItem(LS_REFRESH) ?? "";
|
|
116
|
+
if (!refresh) {
|
|
117
|
+
if (refreshToken.value) clearSession();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (refresh !== refreshToken.value) adoptStoredSession();
|
|
121
|
+
else if (access !== accessToken.value) adoptStoredSession();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 后台标签页的定时器会被浏览器推迟,回到前台时补一次续期。 */
|
|
125
|
+
function onVisible() {
|
|
126
|
+
if (document.visibilityState !== "visible" || !refreshToken.value) return;
|
|
127
|
+
if (renewDueAt && Date.now() >= renewDueAt) void renew();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 采用别的标签页刚写入的令牌,不再自己去 Auth 换。 */
|
|
131
|
+
function adoptStoredSession(): boolean {
|
|
132
|
+
const access = localStorage.getItem(LS_ACCESS) ?? "";
|
|
133
|
+
const refresh = localStorage.getItem(LS_REFRESH) ?? "";
|
|
134
|
+
if (!access || !refresh || tokenExpiresAt(access) <= Date.now())
|
|
135
|
+
return false;
|
|
136
|
+
accessToken.value = access;
|
|
137
|
+
refreshToken.value = refresh;
|
|
138
|
+
const stored = readStoredUser();
|
|
139
|
+
if (stored) user.value = stored;
|
|
140
|
+
renewRetryMs = 0;
|
|
141
|
+
scheduleRenew();
|
|
142
|
+
return true;
|
|
51
143
|
}
|
|
52
144
|
|
|
53
145
|
interface SnapshotData {
|
|
@@ -126,17 +218,48 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
126
218
|
async function waitUntilConnected(timeoutMs = 10000): Promise<void> {
|
|
127
219
|
if (connected.value) return;
|
|
128
220
|
if (!ws) throw new Error("未连接");
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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
|
+
}
|
|
140
263
|
}
|
|
141
264
|
|
|
142
265
|
async function changeMyPassword(
|
|
@@ -162,37 +285,94 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
162
285
|
|
|
163
286
|
function setSession(result: LoginResult) {
|
|
164
287
|
sessionMessage.value = "";
|
|
165
|
-
if (result.user)
|
|
288
|
+
if (result.user) {
|
|
289
|
+
user.value = result.user;
|
|
290
|
+
localStorage.setItem(LS_USER, JSON.stringify(result.user));
|
|
291
|
+
}
|
|
166
292
|
accessToken.value = result.access_token;
|
|
167
293
|
refreshToken.value = result.refresh_token;
|
|
168
294
|
localStorage.setItem(LS_ACCESS, result.access_token);
|
|
169
295
|
localStorage.setItem(LS_REFRESH, result.refresh_token);
|
|
296
|
+
renewOnConnect = false;
|
|
297
|
+
renewRetryMs = 0;
|
|
170
298
|
scheduleRenew(result.access_expires_in);
|
|
171
299
|
}
|
|
172
300
|
|
|
173
|
-
|
|
301
|
+
/** 剩余寿命过半就续期(15 分钟的令牌约在 7.5 分钟时续),Auth 重启或短暂断网都在余量之内。 */
|
|
302
|
+
function renewLeadMs(expiresAt: number): number {
|
|
303
|
+
return Math.max(0, (expiresAt - Date.now()) / 2);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function scheduleRenew(ttlSeconds = 0) {
|
|
307
|
+
if (renewTimer) clearTimeout(renewTimer);
|
|
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
|
+
);
|
|
314
|
+
renewDueAt = Date.now() + delay;
|
|
315
|
+
renewTimer = setTimeout(() => void renew(), delay);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function scheduleRetry() {
|
|
174
319
|
if (renewTimer) clearTimeout(renewTimer);
|
|
175
|
-
|
|
176
|
-
|
|
320
|
+
renewRetryMs = Math.min(
|
|
321
|
+
renewRetryMs ? renewRetryMs * 2 : 2_000,
|
|
322
|
+
RENEW_RETRY_MAX_MS,
|
|
323
|
+
);
|
|
324
|
+
renewDueAt = Date.now() + renewRetryMs;
|
|
325
|
+
renewTimer = setTimeout(
|
|
326
|
+
() => void renew(),
|
|
327
|
+
renewRetryMs + Math.random() * 1_000,
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** 等别的标签页把轮换后的刷新令牌写进来。并发续期时只有一个标签页能用旧令牌换成功。 */
|
|
332
|
+
async function waitForOtherTab(
|
|
333
|
+
usedToken: string,
|
|
334
|
+
timeoutMs = 3_000,
|
|
335
|
+
): Promise<boolean> {
|
|
336
|
+
const deadline = Date.now() + timeoutMs;
|
|
337
|
+
while (Date.now() < deadline) {
|
|
338
|
+
const stored = localStorage.getItem(LS_REFRESH) ?? "";
|
|
339
|
+
if (stored && stored !== usedToken && adoptStoredSession()) return true;
|
|
340
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
341
|
+
}
|
|
342
|
+
return false;
|
|
177
343
|
}
|
|
178
344
|
|
|
179
|
-
|
|
180
|
-
|
|
345
|
+
function renew(): Promise<void> {
|
|
346
|
+
renewing ??= doRenew().finally(() => {
|
|
347
|
+
renewing = null;
|
|
348
|
+
});
|
|
349
|
+
return renewing;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async function doRenew() {
|
|
353
|
+
if (!refreshToken.value) return;
|
|
354
|
+
const stored = localStorage.getItem(LS_REFRESH) ?? "";
|
|
355
|
+
if (stored && stored !== refreshToken.value && adoptStoredSession()) return;
|
|
356
|
+
// 刚回到前台时连接可能正在恢复,先等一会儿再续期,不要直接放弃。
|
|
357
|
+
if (!ws || !(await ws.waitReady())) {
|
|
358
|
+
scheduleRetry();
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
const used = refreshToken.value;
|
|
181
362
|
try {
|
|
182
363
|
const result = (await ws.call("refresh", {
|
|
183
|
-
refresh_token:
|
|
364
|
+
refresh_token: used,
|
|
184
365
|
})) as LoginResult;
|
|
185
|
-
|
|
186
|
-
accessToken.value = result.access_token;
|
|
187
|
-
refreshToken.value = result.refresh_token;
|
|
188
|
-
localStorage.setItem(LS_ACCESS, result.access_token);
|
|
189
|
-
localStorage.setItem(LS_REFRESH, result.refresh_token);
|
|
190
|
-
scheduleRenew(result.access_expires_in);
|
|
366
|
+
setSession(result);
|
|
191
367
|
} catch (error) {
|
|
368
|
+
if (!(error instanceof YsRpcError) || !RENEW_REJECTED.has(error.code)) {
|
|
369
|
+
// Auth 正在重启或网络抖动:保留登录态,令牌还有半个寿命的余量,稍后再试。
|
|
370
|
+
scheduleRetry();
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
if (error.code === RENEW_USED && (await waitForOtherTab(used))) return;
|
|
192
374
|
clearSession();
|
|
193
|
-
sessionMessage.value =
|
|
194
|
-
.replace(/^Error:\s*/, "")
|
|
195
|
-
.replace(/^\[\d+\]\s*/, "");
|
|
375
|
+
sessionMessage.value = error.clientMessage;
|
|
196
376
|
}
|
|
197
377
|
}
|
|
198
378
|
|
|
@@ -219,8 +399,12 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
219
399
|
refreshToken.value = "";
|
|
220
400
|
localStorage.removeItem(LS_ACCESS);
|
|
221
401
|
localStorage.removeItem(LS_REFRESH);
|
|
402
|
+
localStorage.removeItem(LS_USER);
|
|
222
403
|
if (renewTimer) clearTimeout(renewTimer);
|
|
223
404
|
renewTimer = null;
|
|
405
|
+
renewRetryMs = 0;
|
|
406
|
+
renewDueAt = 0;
|
|
407
|
+
renewOnConnect = false;
|
|
224
408
|
}
|
|
225
409
|
|
|
226
410
|
return {
|
|
@@ -236,6 +420,8 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
236
420
|
login,
|
|
237
421
|
loginByCode,
|
|
238
422
|
waitUntilConnected,
|
|
423
|
+
freshToken,
|
|
424
|
+
call,
|
|
239
425
|
changeMyPassword,
|
|
240
426
|
renew,
|
|
241
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);
|