1
>
/*---------------------------------------------------------------------------------------------
cacheState.ts
2
>
* Copyright (c) Microsoft Corporation. All rights reserved.
3
>
* Licensed under the MIT License. See License.txt in the project root for license information.
4
>
*--------------------------------------------------------------------------------------------*/
5
>
6
>
import { defaultGenerator } from '../../../../base/common/idGenerator.js';
7
>
import { IFileQuery } from '../../../services/search/common/search.js';
8
>
import { equals } from '../../../../base/common/objects.js';
9
>
10
>
enum LoadingPhase {
11
>
Created = 1,
12
>
Loading = 2,
13
>
Loaded = 3,
14
>
Errored = 4,
15
>
Disposed = 5
16
>
}
17
>
18
>
export class FileQueryCacheState {
19
>
20
>
private readonly _cacheKey;
21
>
get cacheKey(): string {
22
>
if (this.loadingPhase === LoadingPhase.Loaded || !this.previousCacheState) {
23
>
return this._cacheKey;
24
>
}
25
26
return this.previousCacheState.cacheKey;
28
>
29
>
get isLoaded(): boolean {
30
>
const isLoaded = this.loadingPhase === LoadingPhase.Loaded;
31
>
32
>
return isLoaded || !this.previousCacheState ? isLoaded : this.previousCacheState.isLoaded;
33
>
}
34
>
35
>
get isUpdating(): boolean {
36
>
const isUpdating = this.loadingPhase === LoadingPhase.Loading;
37
>
38
>
return isUpdating || !this.previousCacheState ? isUpdating : this.previousCacheState.isUpdating;
39
>
}
40
>
41
>
private readonly query;
42
>
43
>
private loadingPhase;
44
>
private loadPromise: Promise<void> | undefined;
45
>
46
>
constructor(
47
>
private cacheQuery: (cacheKey: string) => IFileQuery,
48
>
private loadFn: (query: IFileQuery) => Promise<unknown>,
49
>
private disposeFn: (cacheKey: string) => Promise<void>,
50
>
private previousCacheState: FileQueryCacheState | undefined
51
>
) {
52
>
this._cacheKey = defaultGenerator.nextId();
53
>
this.query = this.cacheQuery(this._cacheKey);
54
>
this.loadingPhase = LoadingPhase.Created;
55
>
if (this.previousCacheState) {
56
>
const current = Object.assign({}, this.query, { cacheKey: null });
57
>
const previous = Object.assign({}, this.previousCacheState.query, { cacheKey: null });
58
>
if (!equals(current, previous)) {
59
this.previousCacheState.dispose();
60
this.previousCacheState = undefined;
61
}
63
>
}
64
>
65
>
load(): FileQueryCacheState {
66
>
if (this.isUpdating) {
67
return this;
68
}
70
>
this.loadingPhase = LoadingPhase.Loading;
71
>
72
>
this.loadPromise = (async () => {
73
>
try {
74
>
await this.loadFn(this.query);
75
>
76
>
this.loadingPhase = LoadingPhase.Loaded;
77
>
78
>
if (this.previousCacheState) {
79
this.previousCacheState.dispose();
80
this.previousCacheState = undefined;
81
}
83
this.loadingPhase = LoadingPhase.Errored;
84
85
throw error;
86
}
88
>
89
>
return this;
90
>
}
91
>
92
>
dispose(): void {
93
if (this.loadPromise) {
94
(async () => {