forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathpersistentState.ts
More file actions
238 lines (218 loc) · 9.47 KB
/
persistentState.ts
File metadata and controls
238 lines (218 loc) · 9.47 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
238
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import { inject, injectable, named, optional } from 'inversify';
import { Memento } from 'vscode';
import { IExtensionSingleActivationService } from '../activation/types';
import { traceError } from '../logging';
import { ICommandManager } from './application/types';
import { Commands } from './constants';
import {
GLOBAL_MEMENTO,
IExtensionContext,
IMemento,
IPersistentState,
IPersistentStateFactory,
WORKSPACE_MEMENTO,
} from './types';
import { cache } from './utils/decorators';
import { noop } from './utils/misc';
import { clearCacheDirectory } from '../pythonEnvironments/base/locators/common/nativePythonFinder';
import { clearCache, useEnvExtension } from '../envExt/api.internal';
let _workspaceState: Memento | undefined;
const _workspaceKeys: string[] = [];
export function initializePersistentStateForTriggers(context: IExtensionContext) {
_workspaceState = context.workspaceState;
}
export function getWorkspaceStateValue<T>(key: string, defaultValue?: T): T | undefined {
if (!_workspaceState) {
throw new Error('Workspace state not initialized');
}
if (defaultValue === undefined) {
return _workspaceState.get<T>(key);
}
return _workspaceState.get<T>(key, defaultValue);
}
export async function updateWorkspaceStateValue<T>(key: string, value: T): Promise<void> {
if (!_workspaceState) {
throw new Error('Workspace state not initialized');
}
try {
_workspaceKeys.push(key);
await _workspaceState.update(key, value);
const after = getWorkspaceStateValue(key);
if (JSON.stringify(after) !== JSON.stringify(value)) {
await _workspaceState.update(key, undefined);
await _workspaceState.update(key, value);
traceError('Error while updating workspace state for key:', key);
}
} catch (ex) {
traceError(`Error while updating workspace state for key [${key}]:`, ex);
}
}
async function clearWorkspaceState(): Promise<void> {
if (_workspaceState !== undefined) {
await Promise.all(_workspaceKeys.map((key) => updateWorkspaceStateValue(key, undefined)));
}
}
export class PersistentState<T> implements IPersistentState<T> {
constructor(
public readonly storage: Memento,
private key: string,
private defaultValue?: T,
private expiryDurationMs?: number,
) {}
public get value(): T {
if (this.expiryDurationMs) {
const cachedData = this.storage.get<{ data?: T; expiry?: number }>(this.key, { data: this.defaultValue! });
if (!cachedData || !cachedData.expiry || cachedData.expiry < Date.now()) {
return this.defaultValue!;
} else {
return cachedData.data!;
}
} else {
return this.storage.get<T>(this.key, this.defaultValue!);
}
}
public async updateValue(newValue: T, retryOnce = true): Promise<void> {
try {
if (this.expiryDurationMs) {
await this.storage.update(this.key, { data: newValue, expiry: Date.now() + this.expiryDurationMs });
} else {
await this.storage.update(this.key, newValue);
}
if (retryOnce && JSON.stringify(this.value) != JSON.stringify(newValue)) {
// Due to a VSCode bug sometimes the changes are not reflected in the storage, atleast not immediately.
// It is noticed however that if we reset the storage first and then update it, it works.
// https://github.com/microsoft/vscode/issues/171827
await this.updateValue(undefined as any, false);
await this.updateValue(newValue, false);
}
} catch (ex) {
traceError('Error while updating storage for key:', this.key, ex);
}
}
}
export const GLOBAL_PERSISTENT_KEYS_DEPRECATED = 'PYTHON_EXTENSION_GLOBAL_STORAGE_KEYS';
export const WORKSPACE_PERSISTENT_KEYS_DEPRECATED = 'PYTHON_EXTENSION_WORKSPACE_STORAGE_KEYS';
export const GLOBAL_PERSISTENT_KEYS = 'PYTHON_GLOBAL_STORAGE_KEYS';
const WORKSPACE_PERSISTENT_KEYS = 'PYTHON_WORKSPACE_STORAGE_KEYS';
type KeysStorageType = 'global' | 'workspace';
export type KeysStorage = { key: string; defaultValue: unknown };
@injectable()
export class PersistentStateFactory implements IPersistentStateFactory, IExtensionSingleActivationService {
public readonly supportedWorkspaceTypes = { untrustedWorkspace: false, virtualWorkspace: true };
public readonly _globalKeysStorage = new PersistentState<KeysStorage[]>(
this.globalState,
GLOBAL_PERSISTENT_KEYS,
[],
);
public readonly _workspaceKeysStorage = new PersistentState<KeysStorage[]>(
this.workspaceState,
WORKSPACE_PERSISTENT_KEYS,
[],
);
constructor(
@inject(IMemento) @named(GLOBAL_MEMENTO) private globalState: Memento,
@inject(IMemento) @named(WORKSPACE_MEMENTO) private workspaceState: Memento,
@inject(ICommandManager) private cmdManager?: ICommandManager,
@inject(IExtensionContext) @optional() private context?: IExtensionContext,
) {}
public async activate(): Promise<void> {
this.cmdManager?.registerCommand(Commands.ClearStorage, async () => {
await clearWorkspaceState();
await this.cleanAllPersistentStates();
if (useEnvExtension()) {
await clearCache();
}
});
const globalKeysStorageDeprecated = this.createGlobalPersistentState(GLOBAL_PERSISTENT_KEYS_DEPRECATED, []);
const workspaceKeysStorageDeprecated = this.createWorkspacePersistentState(
WORKSPACE_PERSISTENT_KEYS_DEPRECATED,
[],
);
// Old storages have grown to be unusually large due to https://github.com/microsoft/vscode-python/issues/17488,
// so reset them. This line can be removed after a while.
if (globalKeysStorageDeprecated.value.length > 0) {
globalKeysStorageDeprecated.updateValue([]).ignoreErrors();
}
if (workspaceKeysStorageDeprecated.value.length > 0) {
workspaceKeysStorageDeprecated.updateValue([]).ignoreErrors();
}
}
public createGlobalPersistentState<T>(
key: string,
defaultValue?: T,
expiryDurationMs?: number,
): IPersistentState<T> {
this.addKeyToStorage('global', key, defaultValue).ignoreErrors();
return new PersistentState<T>(this.globalState, key, defaultValue, expiryDurationMs);
}
public createWorkspacePersistentState<T>(
key: string,
defaultValue?: T,
expiryDurationMs?: number,
): IPersistentState<T> {
this.addKeyToStorage('workspace', key, defaultValue).ignoreErrors();
return new PersistentState<T>(this.workspaceState, key, defaultValue, expiryDurationMs);
}
/**
* Note we use a decorator to cache the promise returned by this method, so it's only called once.
* It is only cached for the particular arguments passed, so the argument type is simplified here.
*/
@cache(-1, true)
private async addKeyToStorage<T>(keyStorageType: KeysStorageType, key: string, defaultValue?: T) {
const storage = keyStorageType === 'global' ? this._globalKeysStorage : this._workspaceKeysStorage;
const found = storage.value.find((value) => value.key === key);
if (!found) {
await storage.updateValue([{ key, defaultValue }, ...storage.value]);
}
}
private async cleanAllPersistentStates(): Promise<void> {
const clearCacheDirPromise = this.context ? clearCacheDirectory(this.context).catch() : Promise.resolve();
await Promise.all(
this._globalKeysStorage.value.map(async (keyContent) => {
const storage = this.createGlobalPersistentState(keyContent.key);
await storage.updateValue(keyContent.defaultValue);
}),
);
await Promise.all(
this._workspaceKeysStorage.value.map(async (keyContent) => {
const storage = this.createWorkspacePersistentState(keyContent.key);
await storage.updateValue(keyContent.defaultValue);
}),
);
await this._globalKeysStorage.updateValue([]);
await this._workspaceKeysStorage.updateValue([]);
await clearCacheDirPromise;
this.cmdManager?.executeCommand('workbench.action.reloadWindow').then(noop);
}
}
/////////////////////////////
// a simpler, alternate API
// for components to use
export interface IPersistentStorage<T> {
get(): T;
set(value: T): Promise<void>;
}
/**
* Build a global storage object for the given key.
*/
export function getGlobalStorage<T>(context: IExtensionContext, key: string, defaultValue?: T): IPersistentStorage<T> {
const globalKeysStorage = new PersistentState<KeysStorage[]>(context.globalState, GLOBAL_PERSISTENT_KEYS, []);
const found = globalKeysStorage.value.find((value) => value.key === key);
if (!found) {
const newValue = [{ key, defaultValue }, ...globalKeysStorage.value];
globalKeysStorage.updateValue(newValue).ignoreErrors();
}
const raw = new PersistentState<T>(context.globalState, key, defaultValue);
return {
// We adapt between PersistentState and IPersistentStorage.
get() {
return raw.value;
},
set(value: T) {
return raw.updateValue(value);
},
};
}