@ysgroup/core 0.1.17 → 0.1.19
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/index.ts +22 -2
- package/src/store.ts +98 -11
- package/src/version.ts +93 -0
- package/src/ws.ts +113 -22
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -1,7 +1,27 @@
|
|
|
1
1
|
/* @ysgroup/core —— 前端运行时:WS RPC 客户端 / 登录态 / 差量订阅 / REST。 */
|
|
2
2
|
|
|
3
|
-
export {
|
|
4
|
-
|
|
3
|
+
export {
|
|
4
|
+
YsWsClient,
|
|
5
|
+
YsRpcError,
|
|
6
|
+
YsOfflineError,
|
|
7
|
+
YsConnectionLostError,
|
|
8
|
+
DEFAULT_CALL_TIMEOUT_MS,
|
|
9
|
+
DEFAULT_OFFLINE_WAIT_MS,
|
|
10
|
+
MIN_CALL_TIMEOUT_MS,
|
|
11
|
+
MAX_CALL_TIMEOUT_MS,
|
|
12
|
+
type Envelope,
|
|
13
|
+
type YsDisconnectInfo,
|
|
14
|
+
type YsWsClientOptions,
|
|
15
|
+
} from "./ws";
|
|
16
|
+
export {
|
|
17
|
+
currentEntry,
|
|
18
|
+
latestEntry,
|
|
19
|
+
hasNewVersion,
|
|
20
|
+
isStaleChunkError,
|
|
21
|
+
reloadPage,
|
|
22
|
+
takeReloadMessage,
|
|
23
|
+
} from "./version";
|
|
24
|
+
export { useYsStore, type YsConnectOptions, type YsCallOptions } from "./store";
|
|
5
25
|
export {
|
|
6
26
|
YsRest,
|
|
7
27
|
YsRestError,
|
package/src/store.ts
CHANGED
|
@@ -2,7 +2,26 @@
|
|
|
2
2
|
import { defineStore } from "pinia";
|
|
3
3
|
import { ref, computed } from "vue";
|
|
4
4
|
import { sealLoginPassword } from "./password";
|
|
5
|
-
import {
|
|
5
|
+
import { hasNewVersion } from "./version";
|
|
6
|
+
import { YsRpcError, YsWsClient, type YsDisconnectInfo } from "./ws";
|
|
7
|
+
|
|
8
|
+
/** 前台每隔这么久检查一次是否有新版本前端;回到前台时距上次超过 1 分钟也检查。 */
|
|
9
|
+
const UPDATE_CHECK_MS = 5 * 60_000;
|
|
10
|
+
const UPDATE_RECHECK_ON_VISIBLE_MS = 60_000;
|
|
11
|
+
|
|
12
|
+
/** connect 的可选项。 */
|
|
13
|
+
export interface YsConnectOptions {
|
|
14
|
+
/** 所有业务调用的默认超时(毫秒),默认 10 秒,收在 1 秒~10 分钟之间。 */
|
|
15
|
+
callTimeoutMs?: number;
|
|
16
|
+
/** 断线时还没发出的请求最多等连接恢复多久(毫秒),默认 2 分钟,覆盖一次部署停机。 */
|
|
17
|
+
offlineWaitMs?: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** call 的可选项。 */
|
|
21
|
+
export interface YsCallOptions {
|
|
22
|
+
/** 只放宽或收紧这一次调用的超时(毫秒),例如导出、批量导入。 */
|
|
23
|
+
timeoutMs?: number;
|
|
24
|
+
}
|
|
6
25
|
|
|
7
26
|
interface LoginResult {
|
|
8
27
|
user?: Record<string, unknown>;
|
|
@@ -60,12 +79,21 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
60
79
|
const accessToken = ref<string>(storedAccess);
|
|
61
80
|
const refreshToken = ref<string>(storedRefresh);
|
|
62
81
|
const connected = ref(false);
|
|
82
|
+
/** 本次断开(或首次连接前)开始的时间,毫秒;连上后为 0。服务状态组件据此决定提示级别。 */
|
|
83
|
+
const disconnectedAt = ref(0);
|
|
84
|
+
/** 本次断开是服务端主动重启(部署中)。 */
|
|
85
|
+
const restarting = ref(false);
|
|
86
|
+
/** 服务端已部署了新版本前端。 */
|
|
87
|
+
const updateAvailable = ref(false);
|
|
63
88
|
const appName = ref("");
|
|
64
89
|
const sessionMessage = ref("");
|
|
65
90
|
/** 差量订阅的表数据:table -> Map<id, doc> */
|
|
66
91
|
const tables = ref<Record<string, Map<string, Record<string, unknown>>>>({});
|
|
67
92
|
|
|
68
93
|
let ws: YsWsClient | null = null;
|
|
94
|
+
let updateTimer: ReturnType<typeof setInterval> | null = null;
|
|
95
|
+
let lastUpdateCheck = 0;
|
|
96
|
+
let checkingUpdate: Promise<boolean> | null = null;
|
|
69
97
|
let renewTimer: ReturnType<typeof setTimeout> | null = null;
|
|
70
98
|
let renewing: Promise<void> | null = null;
|
|
71
99
|
let renewRetryMs = 0;
|
|
@@ -79,18 +107,35 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
79
107
|
return Array.from(tables.value[table]?.values() ?? []);
|
|
80
108
|
}
|
|
81
109
|
|
|
82
|
-
function connect(wsUrl: string, app: string) {
|
|
110
|
+
function connect(wsUrl: string, app: string, options: YsConnectOptions = {}) {
|
|
83
111
|
appName.value = app;
|
|
84
|
-
ws = new YsWsClient(wsUrl
|
|
112
|
+
ws = new YsWsClient(wsUrl, {
|
|
113
|
+
callTimeoutMs: options.callTimeoutMs,
|
|
114
|
+
offlineWaitMs: options.offlineWaitMs,
|
|
115
|
+
});
|
|
116
|
+
disconnectedAt.value = Date.now();
|
|
117
|
+
let everConnected = false;
|
|
85
118
|
ws.on("__connected", () => {
|
|
86
119
|
connected.value = true;
|
|
120
|
+
disconnectedAt.value = 0;
|
|
121
|
+
restarting.value = false;
|
|
122
|
+
// 断线重连后检查一次前端版本:部署会重启服务端,重连正是新版本上线的时刻。
|
|
123
|
+
if (everConnected) void checkUpdate();
|
|
124
|
+
everConnected = true;
|
|
87
125
|
if (
|
|
88
126
|
refreshToken.value &&
|
|
89
127
|
(renewOnConnect || !user.value || renewRetryMs > 0)
|
|
90
128
|
)
|
|
91
129
|
void renew();
|
|
92
130
|
});
|
|
93
|
-
ws.on("__disconnected", () =>
|
|
131
|
+
ws.on("__disconnected", (data: unknown) => {
|
|
132
|
+
connected.value = false;
|
|
133
|
+
if (!disconnectedAt.value) disconnectedAt.value = Date.now();
|
|
134
|
+
if ((data as YsDisconnectInfo | null)?.restarting)
|
|
135
|
+
restarting.value = true;
|
|
136
|
+
});
|
|
137
|
+
if (!updateTimer)
|
|
138
|
+
updateTimer = setInterval(() => void checkUpdate(), UPDATE_CHECK_MS);
|
|
94
139
|
ws.on("snapshot", (d: unknown) => applySnapshot(d as SnapshotData));
|
|
95
140
|
ws.on("delta", (d: unknown) => applyDelta(d as DeltaData));
|
|
96
141
|
ws.on("user_revoked", (d: unknown) =>
|
|
@@ -123,7 +168,10 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
123
168
|
|
|
124
169
|
/** 后台标签页的定时器会被浏览器推迟,回到前台时补一次续期。 */
|
|
125
170
|
function onVisible() {
|
|
126
|
-
if (document.visibilityState !== "visible"
|
|
171
|
+
if (document.visibilityState !== "visible") return;
|
|
172
|
+
if (Date.now() - lastUpdateCheck > UPDATE_RECHECK_ON_VISIBLE_MS)
|
|
173
|
+
void checkUpdate();
|
|
174
|
+
if (!refreshToken.value) return;
|
|
127
175
|
if (renewDueAt && Date.now() >= renewDueAt) void renew();
|
|
128
176
|
}
|
|
129
177
|
|
|
@@ -215,10 +263,41 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
215
263
|
setSession(result);
|
|
216
264
|
}
|
|
217
265
|
|
|
218
|
-
|
|
266
|
+
/**
|
|
267
|
+
* 检查服务端是否已有新版本前端,有就把 updateAvailable 置为 true(只升不降)。
|
|
268
|
+
* 后台标签页不检查;同时只跑一次。
|
|
269
|
+
*/
|
|
270
|
+
async function checkUpdate(): Promise<boolean> {
|
|
271
|
+
if (updateAvailable.value) return true;
|
|
272
|
+
if (
|
|
273
|
+
typeof document !== "undefined" &&
|
|
274
|
+
document.visibilityState === "hidden"
|
|
275
|
+
)
|
|
276
|
+
return false;
|
|
277
|
+
if (checkingUpdate) return checkingUpdate;
|
|
278
|
+
lastUpdateCheck = Date.now();
|
|
279
|
+
checkingUpdate = hasNewVersion()
|
|
280
|
+
.then((found) => {
|
|
281
|
+
if (found) updateAvailable.value = true;
|
|
282
|
+
return found;
|
|
283
|
+
})
|
|
284
|
+
.finally(() => {
|
|
285
|
+
checkingUpdate = null;
|
|
286
|
+
});
|
|
287
|
+
return checkingUpdate;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** 「立即重试」:跳过退避马上重连。 */
|
|
291
|
+
function retryNow(): void {
|
|
292
|
+
ws?.retryNow();
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** 默认最多等一个调用超时(connect 时配置,默认 10 秒)。 */
|
|
296
|
+
async function waitUntilConnected(timeoutMs?: number): Promise<void> {
|
|
219
297
|
if (connected.value) return;
|
|
220
298
|
if (!ws) throw new Error("未连接");
|
|
221
|
-
if (!(await ws.waitReady(timeoutMs)))
|
|
299
|
+
if (!(await ws.waitReady(timeoutMs ?? ws.timeoutMs)))
|
|
300
|
+
throw new Error("连接服务超时");
|
|
222
301
|
}
|
|
223
302
|
|
|
224
303
|
/**
|
|
@@ -236,17 +315,20 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
236
315
|
/**
|
|
237
316
|
* 业务请求统一入口:自动带上新鲜的 Access Token。
|
|
238
317
|
* 服务端回「令牌无效」时业务处理尚未执行,续期一次后重试一次是安全的。
|
|
318
|
+
* 慢操作传 `{ timeoutMs }` 只放宽这一次,不要为它调大全局超时。
|
|
239
319
|
*/
|
|
240
320
|
async function call<T = unknown>(
|
|
241
321
|
event: string,
|
|
242
322
|
data: Record<string, unknown> = {},
|
|
323
|
+
options: YsCallOptions = {},
|
|
243
324
|
): Promise<T> {
|
|
244
325
|
if (!ws) throw new Error("未连接");
|
|
245
326
|
const send = async () =>
|
|
246
|
-
(await ws!.call(
|
|
247
|
-
|
|
248
|
-
access_token: await freshToken(),
|
|
249
|
-
|
|
327
|
+
(await ws!.call(
|
|
328
|
+
event,
|
|
329
|
+
{ ...data, access_token: await freshToken() },
|
|
330
|
+
options.timeoutMs,
|
|
331
|
+
)) as T;
|
|
250
332
|
try {
|
|
251
333
|
return await send();
|
|
252
334
|
} catch (error) {
|
|
@@ -412,6 +494,11 @@ export const useYsStore = defineStore("ys", () => {
|
|
|
412
494
|
accessToken,
|
|
413
495
|
refreshToken,
|
|
414
496
|
connected,
|
|
497
|
+
disconnectedAt,
|
|
498
|
+
restarting,
|
|
499
|
+
updateAvailable,
|
|
500
|
+
checkUpdate,
|
|
501
|
+
retryNow,
|
|
415
502
|
isLoggedIn,
|
|
416
503
|
sessionMessage,
|
|
417
504
|
tables,
|
package/src/version.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 前端版本检测与安全重载。
|
|
3
|
+
*
|
|
4
|
+
* 不需要后端配合:当前页面的入口脚本地址(构建产物带哈希,如 /assets/index-abc.js)就是版本。
|
|
5
|
+
* 取一次最新的首页 HTML(不走缓存),入口脚本地址不同就说明重新部署过前端。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const ENTRY_SCRIPT =
|
|
9
|
+
/<script[^>]+type=["']module["'][^>]*\ssrc=["']([^"']+)["']/i;
|
|
10
|
+
const RELOAD_GUARD_KEY = "ys_reload_guard_at";
|
|
11
|
+
const RELOAD_MESSAGE_KEY = "ys_reload_message";
|
|
12
|
+
/** 这段时间内已经自动重载过,就不再自动重载,避免服务端异常时反复刷新。 */
|
|
13
|
+
const RELOAD_GUARD_MS = 20_000;
|
|
14
|
+
|
|
15
|
+
/** 当前页面运行的入口脚本地址;开发模式(/src/main.ts)同样适用,前后一致即视为未更新。 */
|
|
16
|
+
export function currentEntry(): string {
|
|
17
|
+
if (typeof document === "undefined") return "";
|
|
18
|
+
const script = document.querySelector<HTMLScriptElement>(
|
|
19
|
+
'script[type="module"][src]',
|
|
20
|
+
);
|
|
21
|
+
return script?.getAttribute("src") ?? "";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 读取服务端最新首页里的入口脚本地址。服务不可用或不是 HTML 时返回空串。 */
|
|
25
|
+
export async function latestEntry(): Promise<string> {
|
|
26
|
+
if (typeof fetch === "undefined" || typeof location === "undefined")
|
|
27
|
+
return "";
|
|
28
|
+
try {
|
|
29
|
+
const url = new URL(location.pathname || "/", location.origin);
|
|
30
|
+
url.searchParams.set("_ys_v", String(Date.now()));
|
|
31
|
+
const response = await fetch(url, {
|
|
32
|
+
cache: "no-store",
|
|
33
|
+
credentials: "same-origin",
|
|
34
|
+
});
|
|
35
|
+
if (
|
|
36
|
+
!response.ok ||
|
|
37
|
+
!(response.headers.get("content-type") ?? "").includes("html")
|
|
38
|
+
)
|
|
39
|
+
return "";
|
|
40
|
+
return ENTRY_SCRIPT.exec(await response.text())?.[1] ?? "";
|
|
41
|
+
} catch {
|
|
42
|
+
return "";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 服务端已有新版本前端时返回 true。 */
|
|
47
|
+
export async function hasNewVersion(): Promise<boolean> {
|
|
48
|
+
const current = currentEntry();
|
|
49
|
+
if (!current) return false;
|
|
50
|
+
const latest = await latestEntry();
|
|
51
|
+
return !!latest && latest !== current;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 页面按需加载的代码文件已不存在(重新部署后文件名变了)或加载失败。 */
|
|
55
|
+
export function isStaleChunkError(error: unknown): boolean {
|
|
56
|
+
const text = String((error as { message?: unknown })?.message ?? error ?? "");
|
|
57
|
+
return /Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|Unable to preload CSS|Loading chunk \S+ failed|ChunkLoadError/i.test(
|
|
58
|
+
text,
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 重新加载页面以使用最新版本前端。hash 给出时先切到该路由(hash 路由系统用 to.fullPath)。
|
|
64
|
+
* message 会在重新加载后由 takeReloadMessage() 取出提示一次。
|
|
65
|
+
* 返回 false 表示短时间内已经自动重载过,这次不再重载(交给页面提示用户手动刷新)。
|
|
66
|
+
*/
|
|
67
|
+
export function reloadPage(
|
|
68
|
+
options: { hash?: string; message?: string; force?: boolean } = {},
|
|
69
|
+
): boolean {
|
|
70
|
+
if (typeof location === "undefined") return false;
|
|
71
|
+
const now = Date.now();
|
|
72
|
+
const last = Number(sessionStorage.getItem(RELOAD_GUARD_KEY) || 0);
|
|
73
|
+
if (!options.force && now - last < RELOAD_GUARD_MS) return false;
|
|
74
|
+
sessionStorage.setItem(RELOAD_GUARD_KEY, String(now));
|
|
75
|
+
if (options.message)
|
|
76
|
+
sessionStorage.setItem(RELOAD_MESSAGE_KEY, options.message);
|
|
77
|
+
if (options.hash)
|
|
78
|
+
history.replaceState(
|
|
79
|
+
history.state,
|
|
80
|
+
"",
|
|
81
|
+
`#${options.hash.replace(/^#/, "")}`,
|
|
82
|
+
);
|
|
83
|
+
location.reload();
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 取出并清除重新加载前留下的提示语。 */
|
|
88
|
+
export function takeReloadMessage(): string {
|
|
89
|
+
if (typeof sessionStorage === "undefined") return "";
|
|
90
|
+
const message = sessionStorage.getItem(RELOAD_MESSAGE_KEY) ?? "";
|
|
91
|
+
sessionStorage.removeItem(RELOAD_MESSAGE_KEY);
|
|
92
|
+
return message;
|
|
93
|
+
}
|
package/src/ws.ts
CHANGED
|
@@ -30,6 +30,28 @@ export class YsRpcError extends Error {
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/** 请求还没发出,连接就一直没恢复:服务端没收到,可以放心重试。 */
|
|
34
|
+
export class YsOfflineError extends Error {
|
|
35
|
+
constructor(message = "服务暂时不可用,请稍后再试") {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = "YsOfflineError";
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 请求已经发出但连接断了:服务端可能已经执行,结果未知,不要自动重试写操作。 */
|
|
42
|
+
export class YsConnectionLostError extends Error {
|
|
43
|
+
constructor(message = "连接中断,操作结果未知,请刷新数据后核对") {
|
|
44
|
+
super(message);
|
|
45
|
+
this.name = "YsConnectionLostError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 断开事件附带的信息。restarting 表示服务端主动重启(关闭码 1012 / 1001),多半是在部署新版本。 */
|
|
50
|
+
export interface YsDisconnectInfo {
|
|
51
|
+
code: number;
|
|
52
|
+
restarting: boolean;
|
|
53
|
+
}
|
|
54
|
+
|
|
33
55
|
type EventHandler = (data: unknown) => void;
|
|
34
56
|
|
|
35
57
|
/** 回到前台、空闲多久没收到任何消息就探测一次。 */
|
|
@@ -39,6 +61,36 @@ const HEARTBEAT_TICK_MS = 10_000;
|
|
|
39
61
|
/** 探测超时。超时即判定连接假死,立即重连。 */
|
|
40
62
|
const PROBE_TIMEOUT_MS = 3_000;
|
|
41
63
|
const RECONNECT_MAX_MS = 30_000;
|
|
64
|
+
/** 服务端重启(部署)期间按这个间隔快速重连,恢复后第一时间连上。 */
|
|
65
|
+
const RESTART_RECONNECT_MS = 1_500;
|
|
66
|
+
/** 服务端「服务重启」「正在离开」的关闭码。 */
|
|
67
|
+
const RESTART_CLOSE_CODES = new Set([1001, 1012]);
|
|
68
|
+
/** 断线时,还没发出的请求最多等连接恢复这么久(默认 2 分钟),覆盖一次部署的停机。 */
|
|
69
|
+
export const DEFAULT_OFFLINE_WAIT_MS = 120_000;
|
|
70
|
+
/** 调用超时:默认 10 秒,可整体配置,也可单次调用覆盖。超出范围的值收到 1 秒~10 分钟之间。 */
|
|
71
|
+
export const DEFAULT_CALL_TIMEOUT_MS = 10_000;
|
|
72
|
+
export const MIN_CALL_TIMEOUT_MS = 1_000;
|
|
73
|
+
export const MAX_CALL_TIMEOUT_MS = 600_000;
|
|
74
|
+
|
|
75
|
+
export interface YsWsClientOptions {
|
|
76
|
+
/** 本连接所有调用的默认超时(毫秒)。不传用 10 秒。 */
|
|
77
|
+
callTimeoutMs?: number;
|
|
78
|
+
/** 断线时还没发出的请求最多等多久(毫秒)。不传用 2 分钟。 */
|
|
79
|
+
offlineWaitMs?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 没给、不是正数时用 fallback;其余收到允许范围内。 */
|
|
83
|
+
export function normalizeTimeout(
|
|
84
|
+
value: number | undefined,
|
|
85
|
+
fallback: number,
|
|
86
|
+
): number {
|
|
87
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
|
|
88
|
+
return fallback;
|
|
89
|
+
return Math.min(
|
|
90
|
+
MAX_CALL_TIMEOUT_MS,
|
|
91
|
+
Math.max(MIN_CALL_TIMEOUT_MS, Math.round(value)),
|
|
92
|
+
);
|
|
93
|
+
}
|
|
42
94
|
|
|
43
95
|
export class YsWsClient {
|
|
44
96
|
private ws: WebSocket | null = null;
|
|
@@ -63,15 +115,48 @@ export class YsWsClient {
|
|
|
63
115
|
if (event.persisted) this.wake();
|
|
64
116
|
};
|
|
65
117
|
|
|
118
|
+
private readonly callTimeout: number;
|
|
119
|
+
private readonly offlineWait: number;
|
|
120
|
+
/** 最近一次断开是否是服务端主动重启,连上 hello 后清除。 */
|
|
121
|
+
private restarting = false;
|
|
122
|
+
|
|
123
|
+
/** 第二个参数可传 `{ callTimeoutMs }`;为兼容旧写法也可直接传毫秒数。 */
|
|
66
124
|
constructor(
|
|
67
125
|
private url: string,
|
|
68
|
-
|
|
69
|
-
) {
|
|
126
|
+
options: YsWsClientOptions | number = {},
|
|
127
|
+
) {
|
|
128
|
+
const raw = typeof options === "number" ? options : options.callTimeoutMs;
|
|
129
|
+
this.callTimeout = normalizeTimeout(raw, DEFAULT_CALL_TIMEOUT_MS);
|
|
130
|
+
this.offlineWait = normalizeTimeout(
|
|
131
|
+
typeof options === "number" ? undefined : options.offlineWaitMs,
|
|
132
|
+
DEFAULT_OFFLINE_WAIT_MS,
|
|
133
|
+
);
|
|
134
|
+
}
|
|
70
135
|
|
|
71
136
|
get connected(): boolean {
|
|
72
137
|
return this.ready;
|
|
73
138
|
}
|
|
74
139
|
|
|
140
|
+
/** 本连接生效的默认调用超时(毫秒)。 */
|
|
141
|
+
get timeoutMs(): number {
|
|
142
|
+
return this.callTimeout;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 断线时还没发出的请求最多等多久(毫秒)。 */
|
|
146
|
+
get offlineWaitMs(): number {
|
|
147
|
+
return this.offlineWait;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 立即重连(跳过退避),用于「立即重试」按钮。 */
|
|
151
|
+
retryNow(): void {
|
|
152
|
+
if (this.stopped || this.ready) return;
|
|
153
|
+
if (this.ws?.readyState === WebSocket.CONNECTING) return;
|
|
154
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
155
|
+
this.reconnectTimer = null;
|
|
156
|
+
this.reconnectDelay = 1000;
|
|
157
|
+
this.connect();
|
|
158
|
+
}
|
|
159
|
+
|
|
75
160
|
start(): void {
|
|
76
161
|
this.stopped = false;
|
|
77
162
|
this.connect();
|
|
@@ -132,27 +217,29 @@ export class YsWsClient {
|
|
|
132
217
|
}
|
|
133
218
|
|
|
134
219
|
/**
|
|
135
|
-
*
|
|
220
|
+
* 断线时发起的请求先等连接恢复(最多一个默认调用超时)再发出:它还没发出去,补发不会重复执行。
|
|
136
221
|
* 已经发出、途中断线的请求结果未知,仍然报错,避免写操作被执行两次。
|
|
222
|
+
* timeoutMs 只管等回复的时间,导出、批量导入这类慢操作单独放宽,不影响等连接的时间。
|
|
137
223
|
*/
|
|
138
224
|
async call(
|
|
139
225
|
event: string,
|
|
140
226
|
data: unknown = {},
|
|
141
|
-
timeoutMs
|
|
227
|
+
timeoutMs?: number,
|
|
142
228
|
): Promise<unknown> {
|
|
143
|
-
|
|
144
|
-
|
|
229
|
+
const limit = normalizeTimeout(timeoutMs, this.callTimeout);
|
|
230
|
+
// 还没发出的请求,服务端肯定没收到,断线时就等连接恢复再发(最多 offlineWaitMs),部署期间用户无感。
|
|
231
|
+
if (!this.ready && !(await this.waitReady(this.offlineWait))) {
|
|
232
|
+
throw new YsOfflineError();
|
|
145
233
|
}
|
|
146
234
|
const ws = this.ws;
|
|
147
|
-
if (!ws || ws.readyState !== WebSocket.OPEN)
|
|
148
|
-
throw new Error("not connected");
|
|
235
|
+
if (!ws || ws.readyState !== WebSocket.OPEN) throw new YsOfflineError();
|
|
149
236
|
const id = `${this.connectionId || "c0"}:${++this.seq}`;
|
|
150
237
|
ws.send(JSON.stringify({ event, id, ts: Date.now() / 1000, data }));
|
|
151
238
|
return new Promise((resolve, reject) => {
|
|
152
239
|
const timer = setTimeout(() => {
|
|
153
240
|
this.pending.delete(id);
|
|
154
|
-
reject(new Error(
|
|
155
|
-
},
|
|
241
|
+
reject(new Error(`请求超时:${event} 超过 ${limit / 1000} 秒没有返回`));
|
|
242
|
+
}, limit);
|
|
156
243
|
this.pending.set(id, {
|
|
157
244
|
resolve: (v) => {
|
|
158
245
|
clearTimeout(timer);
|
|
@@ -240,13 +327,15 @@ export class YsWsClient {
|
|
|
240
327
|
if (!this.stopped) this.connect();
|
|
241
328
|
}
|
|
242
329
|
|
|
243
|
-
private handleClosed(): void {
|
|
330
|
+
private handleClosed(code = 0): void {
|
|
244
331
|
for (const p of this.pending.values())
|
|
245
|
-
p.reject(new
|
|
332
|
+
p.reject(new YsConnectionLostError());
|
|
246
333
|
this.pending.clear();
|
|
247
334
|
const wasReady = this.ready;
|
|
248
335
|
this.ready = false;
|
|
249
|
-
if (
|
|
336
|
+
if (RESTART_CLOSE_CODES.has(code)) this.restarting = true;
|
|
337
|
+
const info: YsDisconnectInfo = { code, restarting: this.restarting };
|
|
338
|
+
if (wasReady || this.ws) this.emit("__disconnected", info);
|
|
250
339
|
}
|
|
251
340
|
|
|
252
341
|
private connect(): void {
|
|
@@ -256,17 +345,18 @@ export class YsWsClient {
|
|
|
256
345
|
this.reconnectDelay = 1000;
|
|
257
346
|
};
|
|
258
347
|
ws.onmessage = (e) => this.onMessage(e);
|
|
259
|
-
ws.onclose = () => {
|
|
348
|
+
ws.onclose = (event?: CloseEvent) => {
|
|
260
349
|
if (ws !== this.ws) return;
|
|
261
|
-
this.handleClosed();
|
|
350
|
+
this.handleClosed(event?.code ?? 0);
|
|
262
351
|
if (!this.stopped) {
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
this.
|
|
269
|
-
|
|
352
|
+
// 服务端在重启(部署)时按固定短间隔重连,不指数退避,恢复后第一时间连上。
|
|
353
|
+
const delay = this.restarting
|
|
354
|
+
? RESTART_RECONNECT_MS
|
|
355
|
+
: this.reconnectDelay + Math.random() * 1000;
|
|
356
|
+
this.reconnectTimer = setTimeout(() => {
|
|
357
|
+
this.reconnectTimer = null;
|
|
358
|
+
this.connect();
|
|
359
|
+
}, delay);
|
|
270
360
|
this.reconnectDelay = Math.min(
|
|
271
361
|
this.reconnectDelay * 2,
|
|
272
362
|
RECONNECT_MAX_MS,
|
|
@@ -305,6 +395,7 @@ export class YsWsClient {
|
|
|
305
395
|
);
|
|
306
396
|
applyPasswordWrap(msg.data);
|
|
307
397
|
this.ready = true;
|
|
398
|
+
this.restarting = false;
|
|
308
399
|
const waiters = this.readyWaiters;
|
|
309
400
|
this.readyWaiters = [];
|
|
310
401
|
for (const resolve of waiters) resolve();
|