forked from stack-auth/stack-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstores.tsx
More file actions
237 lines (205 loc) · 6.96 KB
/
stores.tsx
File metadata and controls
237 lines (205 loc) · 6.96 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
import { ReadWriteLock } from "./locks";
import { ReactPromise, pending, rejected, resolved } from "./promises";
import { AsyncResult, Result } from "./results";
import { generateUuid } from "./uuids";
export type ReadonlyStore<T> = {
get(): T,
onChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void },
onceChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void },
};
export type AsyncStoreStateChangeCallback<T> = (args: { state: AsyncResult<T>, oldState: AsyncResult<T>, lastOkValue: T | undefined }) => void;
export type ReadonlyAsyncStore<T> = {
isAvailable(): boolean,
get(): AsyncResult<T, unknown, void>,
getOrWait(): ReactPromise<T>,
onChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void },
onceChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void },
onStateChange(callback: AsyncStoreStateChangeCallback<T>): { unsubscribe: () => void },
onceStateChange(callback: AsyncStoreStateChangeCallback<T>): { unsubscribe: () => void },
};
export class Store<T> implements ReadonlyStore<T> {
private readonly _callbacks: Map<string, ((value: T, oldValue: T | undefined) => void)> = new Map();
constructor(
private _value: T
) {}
get(): T {
return this._value;
}
set(value: T): void {
const oldValue = this._value;
this._value = value;
this._callbacks.forEach((callback) => callback(value, oldValue));
}
update(updater: (value: T) => T): T {
const value = updater(this._value);
this.set(value);
return value;
}
onChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {
const uuid = generateUuid();
this._callbacks.set(uuid, callback);
return {
unsubscribe: () => {
this._callbacks.delete(uuid);
},
};
}
onceChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {
const { unsubscribe } = this.onChange((...args) => {
unsubscribe();
callback(...args);
});
return { unsubscribe };
}
}
export const storeLock = new ReadWriteLock();
export class AsyncStore<T> implements ReadonlyAsyncStore<T> {
private _isAvailable: boolean;
private _mostRecentOkValue: T | undefined = undefined;
private _isRejected = false;
private _rejectionError: unknown;
private readonly _waitingRejectFunctions = new Map<string, ((error: unknown) => void)>();
private readonly _callbacks: Map<string, AsyncStoreStateChangeCallback<T>> = new Map();
private _updateCounter = 0;
private _lastSuccessfulUpdate = -1;
constructor(...args: [] | [T]) {
if (args.length === 0) {
this._isAvailable = false;
} else {
this._isAvailable = true;
this._mostRecentOkValue = args[0];
}
}
isAvailable(): boolean {
return this._isAvailable;
}
isRejected(): boolean {
return this._isRejected;
}
get() {
if (this.isRejected()) {
return AsyncResult.error(this._rejectionError);
} else if (this.isAvailable()) {
return AsyncResult.ok(this._mostRecentOkValue as T);
} else {
return AsyncResult.pending();
}
}
getOrWait(): ReactPromise<T> {
const uuid = generateUuid();
if (this.isRejected()) {
return rejected(this._rejectionError);
} else if (this.isAvailable()) {
return resolved(this._mostRecentOkValue as T);
}
const promise = new Promise<T>((resolve, reject) => {
this.onceChange((value) => {
resolve(value);
});
this._waitingRejectFunctions.set(uuid, reject);
});
const withFinally = promise.finally(() => {
this._waitingRejectFunctions.delete(uuid);
});
return pending(withFinally);
}
_setIfLatest(result: Result<T>, curCounter: number) {
const oldState = this.get();
const oldValue = this._mostRecentOkValue;
if (curCounter > this._lastSuccessfulUpdate) {
switch (result.status) {
case "ok": {
if (!this._isAvailable || this._isRejected || this._mostRecentOkValue !== result.data) {
this._lastSuccessfulUpdate = curCounter;
this._isAvailable = true;
this._isRejected = false;
this._mostRecentOkValue = result.data;
this._rejectionError = undefined;
this._callbacks.forEach((callback) => callback({
state: this.get(),
oldState,
lastOkValue: oldValue,
}));
return true;
}
return false;
}
case "error": {
this._lastSuccessfulUpdate = curCounter;
this._isAvailable = false;
this._isRejected = true;
this._rejectionError = result.error;
this._waitingRejectFunctions.forEach((reject) => reject(result.error));
this._callbacks.forEach((callback) => callback({
state: this.get(),
oldState,
lastOkValue: oldValue,
}));
return true;
}
}
}
return false;
}
set(value: T): void {
this._setIfLatest(Result.ok(value), ++this._updateCounter);
}
update(updater: (value: T | undefined) => T): T {
const value = updater(this._mostRecentOkValue);
this.set(value);
return value;
}
async setAsync(promise: Promise<T>): Promise<boolean> {
return await storeLock.withReadLock(async () => {
const curCounter = ++this._updateCounter;
const result = await Result.fromPromise(promise);
return this._setIfLatest(result, curCounter);
});
}
setUnavailable(): void {
this._lastSuccessfulUpdate = ++this._updateCounter;
this._isAvailable = false;
this._isRejected = false;
this._rejectionError = undefined;
}
setRejected(error: unknown): void {
this._setIfLatest(Result.error(error), ++this._updateCounter);
}
map<U>(mapper: (value: T) => U): AsyncStore<U> {
const store = new AsyncStore<U>();
this.onChange((value) => {
store.set(mapper(value));
});
return store;
}
onChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {
return this.onStateChange(({ state, lastOkValue }) => {
if (state.status === "ok") {
callback(state.data, lastOkValue);
}
});
}
onStateChange(callback: AsyncStoreStateChangeCallback<T>): { unsubscribe: () => void } {
const uuid = generateUuid();
this._callbacks.set(uuid, callback);
return {
unsubscribe: () => {
this._callbacks.delete(uuid);
},
};
}
onceChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {
const { unsubscribe } = this.onChange((...args) => {
unsubscribe();
callback(...args);
});
return { unsubscribe };
}
onceStateChange(callback: AsyncStoreStateChangeCallback<T>): { unsubscribe: () => void } {
const { unsubscribe } = this.onStateChange((...args) => {
unsubscribe();
callback(...args);
});
return { unsubscribe };
}
}