-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathplugins-key-value-storage.ts
161 lines (140 loc) · 5.87 KB
/
plugins-key-value-storage.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
// *****************************************************************************
// Copyright (C) 2018 Red Hat, Inc. and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************
import { injectable, inject, postConstruct } from '@theia/core/shared/inversify';
import { FileSystemLocking } from '@theia/core/lib/node';
import * as fs from '@theia/core/shared/fs-extra';
import * as path from 'path';
import { FileUri } from '@theia/core/lib/common/file-uri';
import { Deferred } from '@theia/core/lib/common/promise-util';
import { EnvVariablesServer } from '@theia/core/lib/common/env-variables';
import { PluginPaths } from './paths/const';
import { PluginPathsService } from '../common/plugin-paths-protocol';
import { KeysToAnyValues, KeysToKeysToAnyValue } from '../../common/types';
import { PluginStorageKind } from '../../common';
export interface Store {
fsPath: string
values: KeysToKeysToAnyValue
}
@injectable()
export class PluginsKeyValueStorage {
private stores: Record<string, Store> = Object.create(null);
private storesToSync = new Set<Store>();
private syncStoresTimeout?: NodeJS.Timeout;
private deferredGlobalDataPath = new Deferred<string | undefined>();
@inject(PluginPathsService)
private pluginPathsService: PluginPathsService;
@inject(EnvVariablesServer)
private envServer: EnvVariablesServer;
@inject(FileSystemLocking)
private fsLocking: FileSystemLocking;
@postConstruct()
protected init(): void {
this.deferredGlobalDataPath.resolve(this.getGlobalDataPath().catch(error => {
console.error('Failed to initialize global state path:', error);
return undefined;
}));
process.once('beforeExit', () => this.dispose());
this.syncStores();
}
async set(key: string, value: KeysToAnyValues, kind: PluginStorageKind): Promise<boolean> {
const store = await this.getStore(kind);
if (!store) {
console.warn('Cannot save data: no opened workspace');
return false;
}
if (value === undefined || Object.keys(value).length === 0) {
delete store.values[key];
} else {
store.values[key] = value;
}
this.storesToSync.add(store);
return true;
}
async get(key: string, kind: PluginStorageKind): Promise<KeysToAnyValues> {
const store = await this.getStore(kind);
return store?.values[key] ?? {};
}
async getAll(kind: PluginStorageKind): Promise<KeysToKeysToAnyValue> {
const store = await this.getStore(kind);
return store?.values ?? {};
}
private async getGlobalDataPath(): Promise<string> {
const configDirUri = await this.envServer.getConfigDirUri();
const globalStorageFsPath = path.join(FileUri.fsPath(configDirUri), PluginPaths.PLUGINS_GLOBAL_STORAGE_DIR);
await fs.ensureDir(globalStorageFsPath);
return path.join(globalStorageFsPath, 'global-state.json');
}
private async initializeStore(storePath: string): Promise<Store> {
return this.fsLocking.lockPath(storePath, async resolved => {
const values = await this.readFromFile(resolved);
return {
values,
fsPath: storePath
};
});
}
private async getStore(kind: PluginStorageKind): Promise<Store | undefined> {
const dataPath = await this.getDataPath(kind);
if (dataPath) {
return this.stores[dataPath] ??= await this.initializeStore(dataPath);
}
}
private syncStores(): void {
this.syncStoresTimeout = setTimeout(async () => {
await Promise.all(Array.from(this.storesToSync, async ({ fsPath, values }) => {
await this.fsLocking.lockPath(fsPath, async storePath => {
await this.writeToFile(storePath, values);
});
}));
this.storesToSync.clear();
if (this.syncStoresTimeout) {
this.syncStores();
}
}, this.getSyncStoreTimeout());
}
private getSyncStoreTimeout(): number {
// 0-10s + 1min
return 10_000 * Math.random() + 60_000;
}
private async getDataPath(kind: PluginStorageKind): Promise<string | undefined> {
if (!kind) {
return this.deferredGlobalDataPath.promise;
}
const storagePath = await this.pluginPathsService.getHostStoragePath(kind.workspace, kind.roots);
if (storagePath) {
return path.join(storagePath, 'workspace-state.json');
}
}
private async readFromFile(pathToFile: string): Promise<KeysToKeysToAnyValue> {
if (!await fs.pathExists(pathToFile)) {
return {};
}
try {
return await fs.readJSON(pathToFile);
} catch (error) {
console.error('Failed to parse data from "', pathToFile, '". Reason:', error);
return {};
}
}
private async writeToFile(pathToFile: string, data: KeysToKeysToAnyValue): Promise<void> {
await fs.ensureDir(path.dirname(pathToFile));
await fs.writeJSON(pathToFile, data);
}
private dispose(): void {
clearTimeout(this.syncStoresTimeout);
this.syncStoresTimeout = undefined;
}
}