This repository has been archived by the owner on Dec 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscribersPromiseCache.ts
161 lines (131 loc) · 5.28 KB
/
subscribersPromiseCache.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
import { Disposable } from '@zajno/common/functions/disposer';
import { Fields } from '@zajno/common/fields';
import logger from '@zajno/common/logger';
import { DeferredGetter } from '@zajno/common/structures/promiseCache';
import { SubscribersMapObservable } from './subscribersMap';
import { PromiseCacheObservable } from './promiseCache';
import { catchPromise } from '@zajno/common/functions/safe';
export type Unsub = () => void;
export type Fetcher<T> = (key: string, cb: (val: T) => Promise<void> | void) => Unsub | Promise<Unsub>;
type ObserveStrategy = boolean | 'short' | number;
export interface IObservingCache<T> {
get(key: string): DeferredGetter<T>;
}
export class SubscribersPromiseCache<T> extends Disposable implements IObservingCache<T> {
private readonly _cache: PromiseCacheObservable<T>;
private readonly _observers: SubscribersMapObservable;
private _observeStrategy: ObserveStrategy = null;
private readonly _observeStrategyOverrides: Record<string, ObserveStrategy> = { };
private _updater: Fields.Updater<T> = null;
constructor(readonly fetcher: Fetcher<T>) {
super();
this._cache = new PromiseCacheObservable(this._fetch);
this._observers = new SubscribersMapObservable(this._subscribe);
this.disposer.add(this._observers);
}
public get loadingCount() { return this._cache.busyCount; }
public get observersCount() { return this._observers.count; }
useObservingStrategy(observe: ObserveStrategy) {
this._observeStrategy = observe;
if (!this._observeStrategy) {
this._observers.clear();
} else {
const currentKeys = this._cache.keys();
const timeout = getObserveTimeout(this._observeStrategy);
currentKeys.forEach(key => catchPromise(this._observers.enable(key, true, timeout)));
}
return this;
}
useUpdater(updater: Fields.Updater<T>) {
this._updater = updater;
this._cache.useObserveItems(updater != null);
return this;
}
getIsCached(key: string) {
return this._cache.hasKey(key);
}
getCurent(key: string) {
return this._cache.getCurrent(key, false);
}
get(key: string, overrideStrategy?: ObserveStrategy, observingStartedPromise?: (p: Promise<void>) => void): DeferredGetter<T> {
if (overrideStrategy !== undefined) {
this._observeStrategyOverrides[key] = overrideStrategy;
}
const strategy = firstDefined(this._observeStrategyOverrides[key], this._observeStrategy);
if (strategy && !this._observers.getIsObserving(key)) {
// ensure observe
if (this._cache.hasKey(key)) {
// the request has been initiated already
const timeout = getObserveTimeout(strategy);
const promise = this._observers.enable(key, true, timeout);
if (observingStartedPromise) {
observingStartedPromise(promise);
}
promise.catch((err: Error) => logger.error('[ObservingCache] Error on starting observe', key, strategy, err));
}
}
return this._cache.getDeferred(key);
}
populate = (key: string, item: T) => {
this._updateItem(key, item);
};
invalidate = (key: string) => {
this._observers.enable(key, false);
this._cache.invalidate(key);
};
private _fetch = async (key: string): Promise<T> => {
let firstLoad = true;
return new Promise<T>((resolve) => {
Promise.resolve<Unsub>(
this.fetcher(key, item => {
if (firstLoad) {
resolve(item);
firstLoad = false;
} else {
this._updateItem(key, item);
}
})
).then(unsub => {
const strategy = firstDefined(this._observeStrategyOverrides[key], this._observeStrategy);
if (!strategy) {
// immediate unsub in case no observing strategy has been set
unsub();
} else {
const timeout = getObserveTimeout(strategy);
this._observers.enable(key, true, timeout, [unsub]);
}
});
});
};
private _subscribe = (key: string) => {
return Promise.all([
this.fetcher(key, item => this._updateItem(key, item)),
]);
};
private _updateItem = (key: string, item: T) => {
if (this._updater != null && item != null) {
const current = this._cache.getCurrent(key, false);
if (current != null) {
const result = this._updater(current, item);
// re-set existing item but with updated contents
this._cache.updateValueDirectly(key, result);
return;
}
}
this._cache.updateValueDirectly(key, item);
};
}
function getObserveTimeout(s: ObserveStrategy) {
if (!s) {
return undefined;
}
return typeof s === 'number'
? s
: (s === 'short'
? 5 * 60 * 1000
: null
);
}
function firstDefined<T>(...values: (T | undefined)[]) {
return values.find(v => v !== undefined);
}