-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycle.ts
More file actions
385 lines (337 loc) · 11 KB
/
Cycle.ts
File metadata and controls
385 lines (337 loc) · 11 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
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import { SetArray } from "#structures/array";
/**
* @author SNIPPIK
* @description Базовый класс цикла
* @class DefaultCycleSystem
* @extends SetArray
* @abstract
* @private
*/
abstract class DefaultCycleSystem<T = unknown> extends SetArray<T> {
/** Последний сохраненный временной интервал */
private lastDelay: number = 0;
/** Следующее запланированное время запуска (в ms, с плавающей точкой) */
private startTime: number = 0;
/** Время для высчитывания */
private tickTime: number = 0;
/** Таймер или функция ожидания */
private timeout: NodeJS.Timeout | NodeJS.Immediate;
/**
* @description Время циклической системы изнутри
* @returns number
* @public
*/
public get insideTime(): number {
return this.startTime + this.tickTime;
};
/**
* @description Метод получения времени для обновления времени цикла
* @default Date.now
* @returns number
* @protected
*/
protected get time(): number {
const startTime = process.hrtime.bigint();
return Number(startTime) / 1_000_000;
};
/**
* @description Последний зафиксированный промежуток выполнения
* @returns number
* @public
*/
public get delay(): number {
return this.lastDelay;
};
/**
* @description Высчитываем задержку шага
* @param duration - Истинное время шага
* @private
*/
private set delay(duration: number) {
// Ожидаемое время следующего запуска (без учета _driftStep/lag)
const expectedNext = this.startTime + this.tickTime + duration;
const now = this.time;
const missed = Math.floor((now - expectedNext) / duration);
const steps = Math.max(1, missed + 1);
const correction = Math.floor(steps * duration);
this.tickTime += correction;
this.lastDelay = correction;
};
/**
* @description Создаем класс и добавляем параметры
* @param options - Параметры для работы класса
* @constructor
* @public
*/
public constructor(public options: TaskCycleConfig<T> | PromiseCycleConfig<T>) {
super();
};
/**
* @description Добавляем элемент в очередь
* @param item - Объект T
* @public
*/
public add(item: T): this {
if (this.has(item)) this.delete(item);
super.add(item);
// Запускаем цикл сразу после добавления первого элемента
if (this.size === 1 && !this.startTime) {
this.startTime = this.time;
setImmediate(this.step);
}
return this;
};
/**
* @description Чистка цикла от всего
* @returns void
* @public
*/
public reset(): void {
this.clear(); // Удаляем все объекты
this.reboot();
};
/**
* @description Подготовка данных цикла для повторного использования
* @private
*/
private reboot = () => {
this.startTime = 0;
this.tickTime = 0;
this.lastDelay = 0;
// Если есть таймер
if (this.timeout) this._clearTimeout();
};
/**
* @description Проверяем время для запуска цикла повторно с учетом дрифта цикла
* @returns void
* @protected
*/
private step = (): void => {
// Проверяем цикл на наличие объектов
if (this.size === 0) return this.reset();
// === STEP ===
this.delay = this._stepCycle();
const delay = Math.max(0, this.insideTime - this.time);
setTimeout(this.step, delay);
};
/**
* @description Удаляем таймер или Immediate
* @protected
*/
protected _clearTimeout = () => {
if (!this.timeout) return;
if ('hasRef' in this.timeout) clearTimeout(this.timeout as NodeJS.Timeout);
else clearImmediate(this.timeout as NodeJS.Immediate);
this.timeout = null;
};
/**
* @description Выполняет шаг цикла с учётом точного времени следующего запуска | Полный запрет на promise
* @returns number
* @protected
* @abstract
*/
protected abstract _stepCycle: () => number;
}
/**
* @author SNIPPIK
* @description Класс для удобного управления циклами
* @class TaskCycle
* @abstract
* @public
*/
export abstract class TaskCycle<T = unknown> extends DefaultCycleSystem<T> {
/**
* @description Добавляем элемент в очередь
* @param item - Объект T
* @returns this
* @public
*/
public add = (item: T): this => {
if (this.options.custom?.push) this.options.custom?.push(item);
else if (this.has(item)) this.delete(item);
super.add(item);
return this;
};
/**
* @description Удаляем элемент из очереди
* @param item - Объект T
* @returns boolean
* @public
*/
public delete = (item: T) => {
const index = this.has(item);
// Если есть объект в базе
if (index) {
if (this.options.custom?.remove) this.options.custom.remove(item);
super.delete(item);
}
return true;
};
/**
* @description Здесь будет выполнен прогон объектов для выполнения execute
* @returns Promise<void>
* @readonly
* @private
*/
protected _stepCycle = () => {
this.options?.custom?.step?.();
// Запускаем цикл
for (const item of this) {
// Если объект не готов
if (!this.options.filter(item)) continue;
try {
this.options.execute(item);
} catch (error) {
this.delete(item);
console.log(error);
}
}
return this.options.duration;
};
}
/**
* @author SNIPPIK
* @description Класс для удобного управления promise циклами
* @class PromiseCycle
* @abstract
* @public
*/
export abstract class PromiseCycle<T = unknown> extends DefaultCycleSystem<T> {
protected get time() { return Date.now(); };
/**
* @description Добавляем элемент в очередь
* @param item - Объект T
* @returns this
* @public
*/
public add = (item: T): this => {
if (this.options.custom?.push) this.options.custom?.push(item);
else if (this.has(item)) this.delete(item);
super.add(item);
return this;
};
/**
* @description Удаляем элемент из очереди
* @param item - Объект T
* @returns boolean
* @public
*/
public delete = (item: T) => {
const index = this.has(item);
// Если есть объект в базе
if (index) {
if (this.options.custom?.remove) this.options.custom.remove(item);
super.delete(item);
}
return true;
};
/**
* @description Здесь будет выполнен прогон объектов для выполнения execute
* @returns Promise<void>
* @readonly
* @private
*/
protected _stepCycle = () => {
for (const item of this) {
if (!this.options.filter(item)) continue;
this.runItem(item);
}
return 30_000;
};
/**
* @description Обработка обещаний
* @param item - объект с обещанием
* @private
*/
private runItem(item: T): void {
(this.options.execute(item) as Promise<boolean>)
.then(ok => {
if (!ok) this.delete(item);
})
.catch(err => {
this.delete(item);
console.error(err);
});
};
}
/**
* @author SNIPPIK
* @description Интерфейс для опций DefaultCycleSystem
* @interface BaseCycleConfig
* @private
*/
interface BaseCycleConfig<T> {
/**
* @description Время прогона цикла, через n времени будет запущен цикл по новой
* @readonly
* @public
*/
duration: number;
/**
* @description Как фильтровать объекты, вдруг объект еще не готов
* @readonly
* @public
*/
readonly filter: (item: T) => boolean;
/**
* @description Кастомные функции, необходимы для модификации или правильного удаления
* @readonly
* @public
*/
readonly custom?: {
/**
* @description Данная функция расширяет функционал добавления, выполняется перед добавлением
* @param item - объект
* @readonly
* @public
*/
readonly push?: (item: T) => void;
/**
* @description Данная функция расширяет функционал удаления, выполняется перед удалением
* @param item - объект
* @readonly
* @public
*/
readonly remove?: (item: T) => void;
/**
* @description Данная функция расширяет функционал шага, выполняется перед шагом
* @readonly
* @public
*/
readonly step?: () => void;
}
}
/**
* @author SNIPPIK
* @description Интерфейс для опций TaskCycle
* @interface TaskCycleConfig
* @private
*/
interface TaskCycleConfig<T> extends BaseCycleConfig<T> {
/**
* @description Функция для выполнения
* @readonly
* @public
*/
readonly execute: (item: T) => Promise<void> | void;
/**
* @description Время прогона цикла, через n времени будет запущен цикл по новой
* @readonly
* @public
*/
duration: number;
}
/**
* @author SNIPPIK
* @description Интерфейс для опций PromiseCycle
* @interface PromiseCycleConfig
* @private
*/
interface PromiseCycleConfig<T> extends BaseCycleConfig<T> {
/**
* @description Функция для выполнения
* @readonly
* @public
*/
readonly execute: (item: T) => Promise<boolean>;
}