cancellation.ts
5.71 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
156
157
/**
* 在途请求取消注册表。
*
* 参考 glsk-fetch 的 AbortSignal 透传 / CANCEL_ERROR 语义,但补上它缺失的两点:
* 1. 它只用一个 Set<string> 存 url,做「相同 url 进行中 → 拒绝后一个」;这里用
* Map<key, AbortController> 真正 **abort 前一个未完成的相同请求**。
* 2. 它没有任何页面/scope 分组,只能靠业务方共享外部 signal;这里按 scope 建索引,
* 菜单/页面切换时一次 cancelRequests(scope) 就能批量中断该页所有在途请求。
*
* key = METHOD:resource:稳定参数哈希(而非只有 url),避免不同筛选条件/分页的
* 并发查询被误判成「相同请求」。
*
* 注册表挂在 globalThis 的 Symbol.for 上:微前端里主壳与每个 iframe 各有自己的
* api-core bundle 副本,各自 realm 独立,正好各管各的在途请求;同一 realm 内即便
* 加载了两份 bundle(主入口 + legacy)也共用一份注册表,取消不会漏。
*/
export interface CancellationReason {
code: 'CANCELLED';
detail: string;
}
export function cancellationError(detail: string): CancellationReason {
return { code: 'CANCELLED', detail };
}
interface Registry {
byKey: Map<string, AbortController>;
byScope: Map<string, Set<AbortController>>;
activeScope?: string;
}
const REGISTRY_KEY = Symbol.for('uj.api-core.cancellation');
function registry(): Registry {
const g = globalThis as unknown as Record<symbol, Registry | undefined>;
if (!g[REGISTRY_KEY]) {
g[REGISTRY_KEY] = { byKey: new Map(), byScope: new Map() };
}
return g[REGISTRY_KEY]!;
}
/** 当前页面 scope:请求未显式带 scope 时自动归到这里。 */
export function setActiveScope(scope?: string): void {
registry().activeScope = scope || undefined;
}
export function getActiveScope(): string | undefined {
return registry().activeScope;
}
/** 稳定序列化:对象按 key 排序,保证参数相同则 key 相同。循环引用降级成字符串。 */
function stable(value: unknown, seen = new WeakSet<object>()): string {
if (value === null || value === undefined) return '';
if (typeof value !== 'object') return String(value);
if (seen.has(value)) return '[Circular]';
seen.add(value);
if (Array.isArray(value)) return `[${value.map((v) => stable(v, seen)).join(',')}]`;
return `{${Object.keys(value)
.sort()
.map((k) => `${k}:${stable((value as Record<string, unknown>)[k], seen)}`)
.join(',')}}`;
}
/** 相同请求判定用的 key:方法 + 资源 + 参数(data 优先,其次 params)。 */
export function requestKey(method: string, resource: string, payload?: unknown): string {
return `${method.toUpperCase()}:${resource}:${stable(payload)}`;
}
export interface RegisterCancellableOptions {
key: string;
controller: AbortController;
scope?: string;
/** 是否取消同 key 的前一个未完成请求(默认 true)。 */
cancelPrevious?: boolean;
/** 传给前一个请求 abort() 的原因。 */
reason?: unknown;
}
/**
* 登记一次在途请求,返回注销函数(必须在 finally 里调用)。
* 若同 key 已有未完成请求且 cancelPrevious 为真,先 abort 它再登记新的。
*/
export function registerCancellable(options: RegisterCancellableOptions): () => void {
const reg = registry();
const { key, controller, scope, cancelPrevious = true, reason } = options;
if (cancelPrevious) {
const previous = reg.byKey.get(key);
if (previous && previous !== controller && !previous.signal.aborted) {
previous.abort(reason ?? cancellationError('被后续相同请求取代'));
}
}
reg.byKey.set(key, controller);
if (scope) {
let set = reg.byScope.get(scope);
if (!set) {
set = new Set();
reg.byScope.set(scope, set);
}
set.add(controller);
}
return () => {
if (reg.byKey.get(key) === controller) reg.byKey.delete(key);
const set = scope ? reg.byScope.get(scope) : undefined;
if (set && scope) {
set.delete(controller);
if (!set.size) reg.byScope.delete(scope);
}
};
}
/**
* 批量取消在途请求。
* - 传 scope:只取消该页面/分组的请求;
* - 不传:取消当前 realm 内所有在途请求(菜单切换、登出用这个)。
* 返回实际被 abort 的请求数。
*/
export function cancelRequests(scope?: string): number {
const reg = registry();
const reason = cancellationError('页面切换,取消在途请求');
const targets = new Set<AbortController>();
if (scope === undefined) {
for (const controller of reg.byKey.values()) targets.add(controller);
for (const set of reg.byScope.values()) for (const controller of set) targets.add(controller);
} else {
for (const controller of reg.byScope.get(scope) ?? []) targets.add(controller);
}
let count = 0;
for (const controller of targets) {
if (controller.signal.aborted) continue;
controller.abort(reason);
count += 1;
}
return count;
}
/** 调试 / 测试用:当前在途请求数。 */
export function activeRequestCount(scope?: string): number {
const reg = registry();
if (scope !== undefined) return reg.byScope.get(scope)?.size ?? 0;
return reg.byKey.size;
}
/**
* 合并外部 signal 与自有 controller:外部 abort 时也联动自有 controller。
* 自有 controller 的 signal 才是往下传给传输层的那一个。
*/
export function linkAbortSignal(controller: AbortController, external?: AbortSignal): AbortSignal {
if (!external) return controller.signal;
if (external.aborted) {
controller.abort(external.reason ?? cancellationError('外部 signal 已中止'));
return controller.signal;
}
external.addEventListener('abort', () => controller.abort(external.reason), { once: true });
return controller.signal;
}