-
Notifications
You must be signed in to change notification settings - Fork 1
/
Protector.ts
100 lines (84 loc) · 2.72 KB
/
Protector.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
import { Tracker } from "./Tracker";
export type ProtectionMode = "ready" | "idle" | "any";
export type ProtectorStatus = "busy" | ProtectorIdleStatus;
export type ProtectorIdleStatus = "created" | "ready" | "disposed";
type ResolveOnIdle = () => void;
export class Protector {
private isBusy = false;
private idleStatus: ProtectorIdleStatus = "created";
private resolveOnIdle: ResolveOnIdle[] = [];
constructor(private tracker: Tracker) {}
public get status(): ProtectorStatus {
return this.isBusy ? "busy" : this.idleStatus;
}
public sync<T extends (...args: any[]) => any>(
func: T,
mode: ProtectionMode = "idle",
then?: ProtectorIdleStatus,
): T {
const self = this;
const wrapped = (...args: any[]) => {
self.enter(mode === "any");
try {
return func.apply(this, args);
} finally {
self.exit(then);
}
};
return wrapped as T;
}
public async<T extends (...args: any[]) => Promise<any>>(
func: T,
mode: ProtectionMode = "ready",
then?: ProtectorIdleStatus,
): T {
const self = this;
const wrapped = async (...args: any[]) => {
self.enter(mode === "any");
try {
if (mode === "ready" && !self.tracker.ready) {
await self.tracker.start();
this.idleStatus = "ready";
}
return await func.apply(this, args);
} finally {
self.exit(then);
}
};
return wrapped as T;
}
public whenIdle = () => {
const self = this;
return new Promise<void>(resolve => {
if (self.isBusy) {
self.resolveOnIdle.push(resolve);
} else {
resolve();
}
});
}
private enter(ignoreDisposed: boolean) {
this.throwIfLocked();
if (!ignoreDisposed) {
this.throwIfDisposed();
}
this.isBusy = true;
}
private exit(then?: ProtectorIdleStatus) {
if (typeof then === "string") {
this.idleStatus = then;
}
this.isBusy = false;
this.resolveOnIdle.forEach(callback => callback());
}
private throwIfLocked() {
if (this.isBusy) {
throw new Error("app-history: Concurrent operation not allowed");
}
}
private throwIfDisposed() {
if (this.idleStatus === "disposed") {
throw new Error("app-history: Operation not allowed after dispose");
}
}
}