/
WorkerSource.worker.ts
220 lines (167 loc) · 5.71 KB
/
WorkerSource.worker.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 { IPinnedServersConfig, IServerView } from "../types";
import { filterList } from "./listFilter";
import { getAllMasterListServers } from "./utils/fetchers";
import { IAutocompleteIndex, IListableServerView } from "./types";
import { IServerListConfig } from "../lists/types";
import { sortList } from "./listSorter";
import { serverView2ListableServerView } from "../transformers";
import { AutocompleteIndexer } from "./autocomplete";
import { shouldPrioritizePinnedServers } from "cfx/base/serverUtils";
import { GameName } from "cfx/base/game";
function postMessageToMainThread(type: string, data: any) {
try {
postMessage({ type, data });
} catch (e) {
console.warn(e, type, data);
}
}
export const ServerResponses = defineEvents(postMessageToMainThread)
.add<'allServersBegin'>()
.add<'allServersChunk', IServerView[]>()
.add<'allServersEnd', IServerView[]>()
.add<'allServersError', string>()
.add<'index', IAutocompleteIndex>()
.add<'list', [string, string[]]>()
export type ServerResponsePayload = typeof ServerResponses.TPayloads;
export interface IServersWorkerInitOptions {
gameName: GameName,
serversChunkSize: number,
}
export class ServersWorker {
private fetching = true;
private serversIndex = new AutocompleteIndexer();
private listableServersMap: Record<string, IListableServerView> = {};
// Sorted server IDs lists to use for further filtering
private sortedLists: Record<string, string[]> = {};
private listsRegistry: Record<string, { id: number, config: IServerListConfig | null }> = {};
private gameName = GameName.FiveM;
private serversChunkSize = 500;
private pinnedServersConfig: IPinnedServersConfig | null = null;
constructor() {
onmessage = (event: MessageEvent) => {
const { type, data } = event.data;
if (typeof this[type] === 'function') {
this[type](...data);
}
};
}
async init(options: IServersWorkerInitOptions) {
this.gameName = options.gameName;
this.serversChunkSize = options.serversChunkSize;
this.refresh();
}
setPinnedServersConfig(config: IPinnedServersConfig | null) {
this.pinnedServersConfig = config;
}
applyListConfig(config: IServerListConfig) {
const listType = config.type;
if (!this.listsRegistry[listType]) {
this.listsRegistry[listType] = {
id: 0,
config,
};
} else {
this.listsRegistry[listType].config = config;
this.listsRegistry[listType].id++;
}
if (!this.fetching) {
this.filterAndSendList(config.type);
}
}
async refresh() {
this.fetching = true;
ServerResponses.send('allServersBegin');
let serversBuffer: IServerView[] = [];
const sendBuffer = () => {
if (serversBuffer.length === 0) {
return;
}
ServerResponses.send('allServersChunk', serversBuffer);
serversBuffer = [];
this.reapplyListConfigs();
};
let chunkTimer = setInterval(sendBuffer, 500);
try {
await getAllMasterListServers(this.gameName, (server: IServerView) => {
this.serversIndex.add(server);
this.listableServersMap[server.id] = serverView2ListableServerView(server);
serversBuffer.push(server);
if (serversBuffer.length === this.serversChunkSize) {
sendBuffer();
}
});
clearInterval(chunkTimer);
ServerResponses.send('allServersEnd', serversBuffer);
ServerResponses.send('index', this.serversIndex.getIndex());
this.reapplyListConfigs();
} catch (e) {
console.error(e);
ServerResponses.send('allServersError', e.message);
} finally {
this.fetching = false;
}
}
private reapplyListConfigs() {
for (const { config } of Object.values(this.listsRegistry)) {
if (config) {
this.createdSortedList(config);
this.filterAndSendList(config.type);
}
}
}
private filterAndSendList(listType: string) {
const list = this.listsRegistry[listType];
if (!list || !list.config) {
return;
}
this.sendList(list.config, list.id, filterList(
this.listableServersMap,
this.getSortedList(list.config),
list.config,
));
}
private getSortedList(config: IServerListConfig): string[] {
const listHash = getSortedListHash(config);
let sortedList = this.sortedLists[listHash];
if (!sortedList) {
sortedList = this.createdSortedList(config);
}
return sortedList;
}
private createdSortedList(config: IServerListConfig): string[] {
return this.sortedLists[getSortedListHash(config)] = sortList(
this.listableServersMap,
this.pinnedServersConfig,
config,
);
}
private async sendList(config: IServerListConfig, id: number, list: string[]) {
await Promise.resolve();
if (this.listsRegistry[config.type].id !== id) {
console.log('Dropping list as not most recent', config.type, id, this.listsRegistry[config.type]);
return;
}
ServerResponses.send('list', [config.type, list]);
}
};
new ServersWorker();
export interface Definition<TMap extends Record<string, any>, TPL extends { type: string, data: any }> {
TEvents: TMap;
TPayloads: TPL;
send<T extends keyof TMap>(type: T, data?: TMap[T]): void;
add<Type extends string, Data = void>(): Definition<TMap & Record<Type, Data>, TPL | { type: Type, data: Data }>;
}
export function defineEvents(send: (type: string, data: any) => void): Definition<{}, { type: never, data: never }> {
const definitions = {
send,
add: () => definitions,
} as any;
return definitions;
}
function getSortedListHash(config: IServerListConfig): string {
let hash = `${config.sortBy}:${config.sortDir}`;
if (shouldPrioritizePinnedServers(config)) {
hash += ':pinsOnTop';
}
return hash;
}