-
Notifications
You must be signed in to change notification settings - Fork 0
/
sharedService.ts
220 lines (184 loc) · 6.93 KB
/
sharedService.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
import { v4 as randomId } from 'uuid';
type ServiceEvent<T> = MessageEvent<
| {
method: T;
args: any[];
id: string;
type: 'request';
}
| {
method: T;
id: string;
type: 'response';
result: any;
error: any;
}
>;
const getBroadcastChannelName = (clientId: string, serviceName: string) =>
`${clientId}-${serviceName}`;
let broadcastChannel: BroadcastChannel | null = null;
const getClientId = async () => {
const id = randomId();
const clientId = await navigator.locks.request(id, { mode: 'exclusive' }, async () => {
const { held } = await navigator.locks.query();
return held?.find((lock) => lock.name === id)?.clientId;
});
navigator.locks.request(clientId, { mode: 'exclusive' }, async () => {
await new Promise(() => {}); // Keep the lock until this context is destroyed
});
return clientId;
};
export default (
serviceName: string,
target: { [method: string | symbol]: (...args: any[]) => any },
onProviderChange?: (isServiceProvider: Promise<boolean>) => any
) => {
type TargetKey = keyof typeof target;
const commonChannel = new BroadcastChannel(`shared-service-common-channel-${serviceName}`);
const requestsInFlight = new Map<
string,
{
method: TargetKey;
args: any[];
resolve: (value: any) => void;
reject: (reason?: any) => void;
}
>();
const getOnRequestListener = (
uuid: string,
resolve: (value: any) => void,
reject: (reason?: any) => void
) => {
const listener = (event: ServiceEvent<TargetKey>) => {
const { id, type } = event.data;
if (id !== uuid || type === 'request') return;
requestsInFlight.delete(uuid);
broadcastChannel?.removeEventListener('message', listener);
if (event.data.error) {
console.error('Error processing request', event.data.error);
return reject(event.data.error);
}
resolve(event.data.result);
};
return listener;
};
let readyResolve: (() => void) | null = null;
const status = {
ready: new Promise<void>((resolve) => {
readyResolve = resolve;
}),
isServiceProvider: new Promise<boolean>((resolve) => {
navigator.locks.query().then((locks) => {
const isProvider = !locks.held?.find((lock) => lock.name === serviceName);
resolve(isProvider);
if (!isProvider) onNotProvider();
});
}),
};
navigator.locks.request(serviceName, { mode: 'exclusive' }, async () => {
await onBecomeProvider();
await new Promise(() => {}); // Keep the lock until this context is destroyed
});
const onNotProvider = async () => {
const clientId = await getClientId();
broadcastChannel = new BroadcastChannel(getBroadcastChannelName(clientId, serviceName));
const register = async () =>
await new Promise<void>((resolve) => {
const onRegisteredListener = (event: MessageEvent) => {
if (event.data.clientId === clientId && event.data.type === 'registered') {
commonChannel.removeEventListener('message', onRegisteredListener);
resolve();
}
};
commonChannel.addEventListener('message', onRegisteredListener);
commonChannel.postMessage({ type: 'register', clientId });
});
commonChannel.addEventListener('message', async (event) => {
if (event.data.type === 'providerChange' && !(await status.isServiceProvider)) {
console.log('Provider change detected. Re-registering with the new one...');
await onProviderChange?.(status.isServiceProvider);
await register();
if (requestsInFlight.size > 0) {
console.log('Requests were in flight when the provider changed. Requeuing...');
requestsInFlight.forEach(async ({ method, args, resolve, reject }, uuid) => {
const onRequestlistener = getOnRequestListener(uuid, resolve, reject);
broadcastChannel?.addEventListener('message', onRequestlistener);
broadcastChannel?.postMessage({ id: uuid, type: 'request', method, args });
});
}
}
});
await register();
readyResolve?.();
readyResolve = null;
};
const onBecomeProvider = async () => {
status.isServiceProvider = Promise.resolve(true);
if (readyResolve === null) {
status.ready = new Promise<void>((resolve) => {
readyResolve = resolve;
});
}
commonChannel.addEventListener('message', async (event) => {
const { clientId, type } = event.data;
if (type !== 'register') return;
const clientChannel = new BroadcastChannel(getBroadcastChannelName(clientId, serviceName));
navigator.locks.request(clientId, { mode: 'exclusive' }, async () => {
// The client has gone. Clean up
clientChannel.close();
});
clientChannel.addEventListener('message', async (event: ServiceEvent<TargetKey>) => {
if (event.data.type === 'response') return;
const { method, args, id } = event.data;
let result: any, error: any;
try {
result = await target[method](...args);
} catch (e) {
error =
e instanceof Error
? Object.fromEntries(Object.getOwnPropertyNames(e).map((k) => [k, (e as any)[k]]))
: e;
}
clientChannel.postMessage({ id, type: 'response', result, error, method });
});
commonChannel.postMessage({ type: 'registered', clientId, serviceName });
});
commonChannel.postMessage({ type: 'providerChange', serviceName });
await onProviderChange?.(status.isServiceProvider);
if (requestsInFlight.size > 0) {
console.log('Requests were in flight when this tab became the provider. Requeuing...');
requestsInFlight.forEach(async ({ method, args, resolve, reject }, uuid) => {
try {
const result = await target[method](...args);
resolve(result);
} catch (error) {
console.error('Error processing request', error);
reject(error);
} finally {
requestsInFlight.delete(uuid);
}
});
}
readyResolve?.();
readyResolve = null;
};
const proxy = new Proxy(target, {
get: (target, method) => {
if (method === 'then' || method === 'catch' || method === 'finally') {
// Return undefined for these methods to allow promise chaining to work correctly
return undefined;
}
return async (...args: any[]) => {
if (await status.isServiceProvider) return await target[method](...args);
return new Promise<any>((resolve, reject) => {
const uuid = randomId();
const onRequestlistener = getOnRequestListener(uuid, resolve, reject);
broadcastChannel?.addEventListener('message', onRequestlistener);
broadcastChannel?.postMessage({ id: uuid, type: 'request', method, args });
requestsInFlight.set(uuid, { method, args, resolve, reject });
});
};
},
});
return { proxy, status };
};