-
Notifications
You must be signed in to change notification settings - Fork 14
/
portDetector.ts
301 lines (270 loc) · 7.17 KB
/
portDetector.ts
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import {
injectable,
inject,
actionIdentifier,
storeKey,
Service,
} from 'reactant';
import { LastAction } from 'reactant-last-action';
import {
loadFullStateActionName,
SharedAppOptions,
syncToClientsName,
} from './constants';
import {
CallbackWithHook,
ClientTransport,
Port,
PortApp,
Transports,
Transport,
ISharedAppOptions,
} from './interfaces';
import { createId } from './utils';
/**
* Port Detector
*
* It provides port detection and client/server port switching functions.
*/
@injectable()
export class PortDetector {
protected portApp?: PortApp;
protected lastHooks?: Set<ReturnType<CallbackWithHook>>;
protected serverCallbacks = new Set<
CallbackWithHook<Required<Transports>['server']>
>();
protected clientCallbacks = new Set<
CallbackWithHook<Required<Transports>['server']>
>();
syncFullStatePromise?: ReturnType<
ClientTransport[typeof loadFullStateActionName]
>;
/**
* previous port
*/
previousPort?: Port;
/**
* client id
*/
clientId: string | null = null;
/**
* allow Disable Sync
*/
allowDisableSync = () => true;
constructor(
@inject(SharedAppOptions) public sharedAppOptions: ISharedAppOptions,
public lastAction: LastAction
) {
this.onClient((transport) => {
this.clientId = createId();
this.syncFullState({ forceSync: false });
const disposeSyncToClients = transport.listen(
syncToClientsName,
async (fullState) => {
if (!fullState) return;
const store = (this as Service)[storeKey];
store!.dispatch({
type: `${actionIdentifier}_${loadFullStateActionName}`,
state: {
...fullState,
// ignore router state sync for last action
router: store!.getState().router,
},
_reactant: actionIdentifier,
});
this.lastAction.sequence =
fullState[this.lastAction.stateKey]._sequence;
}
);
return () => {
disposeSyncToClients?.();
this.previousPort = 'client';
};
});
this.onServer(() => {
this.clientId = null;
return () => {
this.previousPort = 'server';
};
});
}
get id() {
return this.clientId ?? '__SERVER__';
}
get shared() {
return !!(this.sharedAppOptions.port && this.sharedAppOptions.type);
}
get name() {
return this.sharedAppOptions.portName ?? 'default';
}
get disableSyncClient() {
return (
document.visibilityState === 'hidden' &&
!this.sharedAppOptions.forcedSyncClient &&
this.allowDisableSync()
);
}
protected detectPort(port: Port) {
return this.portApp?.[port];
}
/**
* onServer
*
* When the port is server, this hook will execute.
* And allow to return a function that will be executed when the current port is switched to client.
*/
onServer = (callback: CallbackWithHook<Required<Transports>['server']>) => {
if (typeof callback !== 'function') {
throw new Error(`'onServer' argument should be a function.`);
}
this.serverCallbacks.add(callback);
if (
this.lastHooks &&
this.lastHooks.size > 0 &&
this.isServer &&
this.transport
) {
try {
const hook = callback(this.transport);
this.lastHooks.add(hook);
} catch (e) {
console.error(e);
}
}
return () => {
this.serverCallbacks.delete(callback);
};
};
/**
* onClient
*
* When the port is client, this hook will execute.
* And allow to return a function that will be executed when the current port is switched to server.
*/
onClient = (callback: CallbackWithHook<Required<Transports>['client']>) => {
if (typeof callback !== 'function') {
throw new Error(`'onClient' argument should be a function.`);
}
this.clientCallbacks.add(callback);
if (
this.lastHooks &&
this.lastHooks.size > 0 &&
this.isClient &&
this.transport
) {
try {
const hook = callback(this.transport);
this.lastHooks.add(hook);
} catch (e) {
console.error(e);
}
}
return () => {
this.clientCallbacks.delete(callback);
};
};
get isWorkerMode() {
return this.sharedAppOptions.type === 'SharedWorker';
}
get isServerWorker() {
return this.isWorkerMode && this.isServer;
}
get isServer() {
return !!this.detectPort('server');
}
get isClient() {
return !!this.detectPort('client');
}
get transports() {
return this.sharedAppOptions.transports ?? {};
}
transport?: Transport;
setPort(
currentPortApp: PortApp,
transport: Required<Transports>[keyof Transports]
) {
this.transport = transport;
if (this.lastHooks) {
for (const hook of this.lastHooks) {
try {
hook?.();
} catch (e) {
console.error(e);
}
}
}
this.lastHooks = new Set();
this.portApp = currentPortApp;
const callbacks = this.isClient
? this.clientCallbacks
: this.serverCallbacks;
for (const callback of callbacks) {
try {
const hook = callback(transport);
this.lastHooks.add(hook);
} catch (e) {
console.error(e);
}
}
}
syncToClients() {
const store = (this as Service)[storeKey];
if (this.transports.server) {
this.transports.server?.emit(
{ name: syncToClientsName, respond: false },
store!.getState()
);
} else {
throw new Error(
`Failed to 'syncToClients()', 'transports.server' does not exist.`
);
}
}
async syncFullState({ forceSync = true } = {}) {
if (forceSync) {
this.syncFullStatePromise = undefined;
}
if (this.syncFullStatePromise) {
await this.syncFullStatePromise;
return;
}
if (typeof this.transports.client === 'undefined') {
throw new Error(`The current client transport does not exist.`);
}
this.syncFullStatePromise = this.transports.client.emit(
loadFullStateActionName,
!forceSync ? this.lastAction.sequence : -1
);
const fullState = await this.syncFullStatePromise;
this.syncFullStatePromise = undefined;
if (typeof fullState === 'undefined') {
throw new Error(`Failed to sync full state from server port.`);
}
if (
fullState === null ||
(!forceSync &&
this.lastAction.sequence >
fullState[this.lastAction.stateKey]._sequence)
)
return;
const store = (this as Service)[storeKey];
store!.dispatch({
type: `${actionIdentifier}_${loadFullStateActionName}`,
// ignore router state sync for last action
state: { ...fullState, router: store!.getState().router },
_reactant: actionIdentifier,
});
this.lastAction.sequence = fullState[this.lastAction.stateKey]._sequence;
}
/**
* transform port with new transport
*/
transform(port: Port, transport?: Transport) {
if (port !== 'server' && port !== 'client') {
throw new Error(`The port '${port}' is not supported.`);
}
this.sharedAppOptions.transports![port] =
transport ?? this.sharedAppOptions.transports![port];
this.sharedAppOptions.transform!(port);
}
}