This repository has been archived by the owner on Apr 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
time.ts
390 lines (362 loc) · 10.9 KB
/
time.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
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
386
387
388
389
390
/** This module is browser compatible. */
import { applyMixins } from "./deps/udibo/mixins/apply.ts";
import { Vector } from "./deps/udibo/collections/vector.ts";
import { RBTree } from "./deps/udibo/collections/trees/rb_tree.ts";
import { ascend } from "./deps/udibo/collections/comparators.ts";
import { delay as delayNative } from "./deps/std/async/delay.ts";
export type NativeDate = Date;
export type NativeDateConstructor = DateConstructor;
export const NativeDate: NativeDateConstructor = Date;
export const NativeTime = {
setTimeout,
clearTimeout,
setInterval,
clearInterval,
};
/** Resolves after the given number of milliseconds using real time. */
export function delay(ms: number): Promise<void> {
return time
? FakeTime.restoreFor(() => {
return delayNative(ms);
})
: delayNative(ms);
}
/** An error related to faking time. */
export class TimeError extends Error {
constructor(message: string) {
super(message);
this.name = "TimeError";
}
}
// deno-lint-ignore no-explicit-any
function isFakeDate(instance: any): instance is FakeDate {
return instance instanceof FakeDate;
}
export interface FakeDate extends NativeDate {
date: Date;
}
export interface FakeDateConstructor extends NativeDateConstructor {
new (): FakeDate;
new (value: string | number | NativeDate): FakeDate;
new (
year: number,
month: number,
date?: number,
hours?: number,
minutes?: number,
seconds?: number,
ms?: number,
): FakeDate;
(): string;
readonly prototype: FakeDate;
parse(s: string): number;
UTC(
year: number,
month: number,
date?: number,
hours?: number,
minutes?: number,
seconds?: number,
ms?: number,
): number;
now(): number;
}
function FakeDateConstructor(this: void): string;
function FakeDateConstructor(this: FakeDate): void;
function FakeDateConstructor(
this: FakeDate,
value: string | number | NativeDate,
): void;
function FakeDateConstructor(
this: FakeDate,
year: number,
month: number,
date?: number,
hours?: number,
minutes?: number,
seconds?: number,
ms?: number,
): void;
function FakeDateConstructor(
this: FakeDate | void,
// deno-lint-ignore no-explicit-any
...args: any[]
): string | void {
if (args.length === 0) args.push(FakeDate.now());
if (isFakeDate(this)) {
this.date = new NativeDate(...(args as []));
} else {
return new NativeDate(args[0]).toString();
}
}
class FakeDateMixin {
static now(): number {
return time?.now ?? NativeDate.now();
}
[Symbol.toPrimitive](this: FakeDate, hint: "default"): string;
[Symbol.toPrimitive](this: FakeDate, hint: "string"): string;
[Symbol.toPrimitive](this: FakeDate, hint: "number"): number;
// deno-lint-ignore no-explicit-any
[Symbol.toPrimitive](this: FakeDate, ...args: any[]): string | number {
return this.date[Symbol.toPrimitive].apply(
this.date,
args as [string],
);
}
}
applyMixins(FakeDateConstructor, [FakeDateMixin]);
export const FakeDate: FakeDateConstructor =
FakeDateConstructor as FakeDateConstructor;
FakeDate.parse = Date.parse;
FakeDate.UTC = Date.UTC;
Object.getOwnPropertyNames(Date.prototype).forEach((name: string) => {
const propName: keyof NativeDate = name as keyof NativeDate;
FakeDate.prototype[propName] = function (
this: FakeDate,
// deno-lint-ignore no-explicit-any
...args: any[]
// deno-lint-ignore no-explicit-any
): any {
// deno-lint-ignore no-explicit-any
return (this.date[propName] as (...args: any[]) => any).apply(
this.date,
args,
);
};
});
function* timerId() {
let i = 1;
while (true) yield i++;
}
interface Timer {
id: number;
// deno-lint-ignore no-explicit-any
callback: (...args: any[]) => void;
delay: number;
// deno-lint-ignore no-explicit-any
args: any[];
due: number;
repeat: boolean;
}
export interface FakeTimeOptions {
/**
* The rate relative to real time at which fake time is updated.
* By default time only moves forward through calling tick or setting now.
* Set to 1 to have the fake time automatically tick foward at the same rate in milliseconds as real time.
*/
advanceRate: number;
/**
* The frequency in milliseconds at which fake time is updated.
* If advanceRate is set, we will update the time every 10 milliseconds by default.
*/
advanceFrequency?: number;
}
interface DueNode {
due: number;
timers: Vector<Timer>;
}
let time: FakeTime | undefined = undefined;
/**
* Overrides the real Date object and timer functions with fake ones that can be
* controlled through the fake time instance.
*/
export class FakeTime {
private _now: number;
private _start: number;
private initializedAt: number;
private advanceRate: number;
private advanceFrequency: number;
private advanceIntervalId?: number;
private timerId: Generator<number>;
private dueNodes: Map<number, DueNode>;
private dueTree: RBTree<DueNode>;
constructor(
start?: number | string | NativeDate | null,
options?: FakeTimeOptions,
) {
FakeTime.restore();
this.initializedAt = NativeDate.now();
this._start = start instanceof NativeDate
? start.valueOf()
: typeof start === "number"
? Math.floor(start)
: typeof start === "string"
? (new Date(start)).valueOf()
: this.initializedAt;
if (Number.isNaN(this._start)) throw new TimeError("invalid start");
this._now = this._start;
this.timerId = timerId();
this.dueNodes = new Map();
this.dueTree = new RBTree(
(a: Partial<DueNode>, b: Partial<DueNode>) => ascend(a.due, b.due),
);
this.overrideGlobals();
time = this;
this.advanceRate = Math.max(
0,
options?.advanceRate ? options.advanceRate : 0,
);
this.advanceFrequency = Math.max(
0,
options?.advanceFrequency ? options.advanceFrequency : 10,
);
if (this.advanceRate > 0) {
this.advanceIntervalId = NativeTime.setInterval.call(null, () => {
this.tick(this.advanceRate * this.advanceFrequency);
}, this.advanceFrequency);
}
}
static restore(): void {
if (time) {
time.restore();
console.error("already using fake time");
}
}
static setTimeout(
// deno-lint-ignore no-explicit-any
callback: (...args: any[]) => void,
delay = 0,
// deno-lint-ignore no-explicit-any
...args: any[]
): number {
if (!time) throw new TimeError("no fake time");
return time.setTimer(callback, delay, args, false);
}
static clearTimeout(id?: number): void {
if (!time) throw new TimeError("no fake time");
if (typeof id === "number" && time.dueNodes.has(id)) {
time.dueNodes.delete(id);
}
}
static setInterval(
// deno-lint-ignore no-explicit-any
callback: (...args: any[]) => void,
delay = 0,
// deno-lint-ignore no-explicit-any
...args: any[]
): number {
if (!time) throw new TimeError("no fake time");
return time.setTimer(callback, delay, args, true);
}
static clearInterval(id?: number): void {
if (!time) throw new TimeError("no fake time");
if (typeof id === "number" && time.dueNodes.has(id)) {
time.dueNodes.delete(id);
}
}
private overrideGlobals(): void {
globalThis.Date = FakeDate;
globalThis.setTimeout = FakeTime.setTimeout;
globalThis.clearTimeout = FakeTime.clearTimeout;
globalThis.setInterval = FakeTime.setInterval;
globalThis.clearInterval = FakeTime.clearInterval;
}
private restoreGlobals(): void {
globalThis.Date = NativeDate;
globalThis.setTimeout = NativeTime.setTimeout;
globalThis.clearTimeout = NativeTime.clearTimeout;
globalThis.setInterval = NativeTime.setInterval;
globalThis.clearInterval = NativeTime.clearInterval;
}
private setTimer(
// deno-lint-ignore no-explicit-any
callback: (...args: any[]) => void,
delay = 0,
// deno-lint-ignore no-explicit-any
args: any[],
repeat = false,
): number {
const id: number = this.timerId.next().value;
delay = Math.max(repeat ? 1 : 0, Math.floor(delay));
const due: number = this.now + delay;
let dueNode: DueNode | null = this.dueTree.find({ due });
if (dueNode === null) {
dueNode = { due, timers: new Vector() };
this.dueTree.insert(dueNode);
}
dueNode.timers.push({
id,
callback,
args,
delay,
due,
repeat,
});
this.dueNodes.set(id, dueNode);
return id;
}
/** Restores real time temporarily until callback returns and resolves. */
static async restoreFor(
// deno-lint-ignore no-explicit-any
callback: (...args: any[]) => Promise<any>,
// deno-lint-ignore no-explicit-any
...args: any[]
// deno-lint-ignore no-explicit-any
): Promise<any> {
if (!time) throw new TimeError("no fake time");
// deno-lint-ignore no-explicit-any
let result: any;
time.restoreGlobals();
try {
result = await callback.apply(null, args);
} finally {
time.overrideGlobals();
}
return result;
}
/**
* The amount of milliseconds elapsed since January 1, 1970 00:00:00 UTC for the fake time.
* When set, it will call any functions waiting to be called between the current and new fake time.
*/
get now(): number {
return this._now;
}
set now(value: number) {
if (value < this._now) throw new Error("time cannot go backwards");
let dueNode: DueNode | null = this.dueTree.min();
while (dueNode && dueNode.due <= value) {
const timer: Timer | undefined = dueNode.timers.shift();
if (timer && this.dueNodes.has(timer.id)) {
this._now = timer.due;
if (timer.repeat) {
const due: number = timer.due + timer.delay;
let dueNode: DueNode | null = this.dueTree.find({ due });
if (dueNode === null) {
dueNode = { due, timers: new Vector() };
this.dueTree.insert(dueNode);
}
dueNode.timers.push({ ...timer, due });
this.dueNodes.set(timer.id, dueNode);
} else {
this.dueNodes.delete(timer.id);
}
timer.callback.apply(null, timer.args);
} else if (!timer) {
this.dueTree.remove(dueNode);
dueNode = this.dueTree.min();
}
}
this._now = value;
}
/** The initial amount of milliseconds elapsed since January 1, 1970 00:00:00 UTC for the fake time. */
get start(): number {
return this._start;
}
set start(value: number) {
throw new Error("cannot change start time after initialization");
}
/**
* Adds the specified number of milliseconds to the fake time.
* This will call any functions waiting to be called between the current and new fake time.
*/
tick(ms = 0) {
this.now += ms;
}
/** Restores time related global functions to their original state. */
restore(): void {
if (!time) throw new TimeError("time already restored");
time = undefined;
this.restoreGlobals();
if (this.advanceIntervalId) clearInterval(this.advanceIntervalId);
}
}