globalStateSync.ts 8.3 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

S
Sandeep Somavarapu 已提交
6
import { IUserData, UserDataSyncError, UserDataSyncErrorCode, SyncStatus, IUserDataSyncStoreService, IUserDataSyncLogService, IGlobalState, SyncSource, IUserDataSynchroniser, ResourceKey } from 'vs/platform/userDataSync/common/userDataSync';
7
import { VSBuffer } from 'vs/base/common/buffer';
S
Sandeep Somavarapu 已提交
8
import { Event } from 'vs/base/common/event';
9
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
S
Sandeep Somavarapu 已提交
10
import { dirname } from 'vs/base/common/resources';
11 12 13 14
import { IFileService } from 'vs/platform/files/common/files';
import { IStringDictionary } from 'vs/base/common/collections';
import { edit } from 'vs/platform/userDataSync/common/content';
import { merge } from 'vs/platform/userDataSync/common/globalStateMerge';
S
Sandeep Somavarapu 已提交
15
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
S
Sandeep Somavarapu 已提交
16
import { parse } from 'vs/base/common/json';
17
import { AbstractSynchroniser } from 'vs/platform/userDataSync/common/abstractSynchronizer';
18
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
19 20 21

const argvProperties: string[] = ['locale'];

22 23 24
interface ISyncPreviewResult {
	readonly local: IGlobalState | undefined;
	readonly remote: IGlobalState | undefined;
S
Sandeep Somavarapu 已提交
25
	readonly remoteUserData: IUserData;
26
	readonly lastSyncUserData: IUserData | null;
27 28
}

29
export class GlobalStateSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser {
30

S
Sandeep Somavarapu 已提交
31
	readonly resourceKey: ResourceKey = 'globalState';
32 33
	protected get enabled(): boolean { return this.configurationService.getValue<boolean>('sync.enableUIState') === true; }

34
	constructor(
35
		@IFileService fileService: IFileService,
S
Sandeep Somavarapu 已提交
36
		@IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
37
		@IUserDataSyncLogService logService: IUserDataSyncLogService,
38
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
S
Sandeep Somavarapu 已提交
39
		@IConfigurationService private readonly configurationService: IConfigurationService,
40
		@ITelemetryService telemetryService: ITelemetryService,
41
	) {
42
		super(SyncSource.GlobalState, fileService, environmentService, userDataSyncStoreService, telemetryService, logService);
43 44 45 46
		this._register(this.fileService.watch(dirname(this.environmentService.argvResource)));
		this._register(Event.filter(this.fileService.onFileChanges, e => e.contains(this.environmentService.argvResource))(() => this._onDidChangeLocal.fire()));
	}

47
	async pull(): Promise<void> {
48
		if (!this.enabled) {
49 50 51 52 53 54 55 56 57 58
			this.logService.info('UI State: Skipped pulling ui state as it is disabled.');
			return;
		}

		this.stop();

		try {
			this.logService.info('UI State: Started pulling ui state...');
			this.setStatus(SyncStatus.Syncing);

59 60
			const lastSyncUserData = await this.getLastSyncUserData();
			const remoteUserData = await this.getRemoteUserData(lastSyncUserData);
61 62 63

			if (remoteUserData.content !== null) {
				const local: IGlobalState = JSON.parse(remoteUserData.content);
64
				await this.apply({ local, remote: undefined, remoteUserData, lastSyncUserData });
65 66 67 68 69 70 71 72 73 74 75 76 77 78
			}

			// No remote exists to pull
			else {
				this.logService.info('UI State: Remote UI state does not exist.');
			}

			this.logService.info('UI State: Finished pulling UI state.');
		} finally {
			this.setStatus(SyncStatus.Idle);
		}
	}

	async push(): Promise<void> {
79
		if (!this.enabled) {
80 81 82 83 84 85 86 87 88 89 90
			this.logService.info('UI State: Skipped pushing UI State as it is disabled.');
			return;
		}

		this.stop();

		try {
			this.logService.info('UI State: Started pushing UI State...');
			this.setStatus(SyncStatus.Syncing);

			const remote = await this.getLocalGlobalState();
91 92 93
			const lastSyncUserData = await this.getLastSyncUserData();
			const remoteUserData = await this.getRemoteUserData(lastSyncUserData);
			await this.apply({ local: undefined, remote, remoteUserData, lastSyncUserData }, true);
94

S
Sandeep Somavarapu 已提交
95
			this.logService.info('UI State: Finished pushing UI State.');
96 97 98 99 100 101
		} finally {
			this.setStatus(SyncStatus.Idle);
		}

	}

S
Sandeep Somavarapu 已提交
102 103
	async stop(): Promise<void> { }

S
Sandeep Somavarapu 已提交
104
	accept(content: string): Promise<void> {
S
Sandeep Somavarapu 已提交
105 106
		throw new Error('UI State: Conflicts should not occur');
	}
107

108 109 110 111 112 113 114 115 116 117 118 119
	async hasLocalData(): Promise<boolean> {
		try {
			const localGloablState = await this.getLocalGlobalState();
			if (localGloablState.argv['locale'] !== 'en') {
				return true;
			}
		} catch (error) {
			/* ignore error */
		}
		return false;
	}

120 121 122 123
	async getRemoteContent(): Promise<string | null> {
		return null;
	}

S
Sandeep Somavarapu 已提交
124
	protected async doSync(remoteUserData: IUserData, lastSyncUserData: IUserData | null): Promise<void> {
125
		try {
S
Sandeep Somavarapu 已提交
126
			const result = await this.getPreview(remoteUserData, lastSyncUserData);
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
			await this.apply(result);
			this.logService.trace('UI State: Finished synchronizing ui state.');
		} catch (e) {
			this.setStatus(SyncStatus.Idle);
			if (e instanceof UserDataSyncError && e.code === UserDataSyncErrorCode.Rejected) {
				// Rejected as there is a new remote version. Syncing again,
				this.logService.info('UI State: Failed to synchronize ui state as there is a new remote version available. Synchronizing again...');
				return this.sync();
			}
			throw e;
		} finally {
			this.setStatus(SyncStatus.Idle);
		}
	}

S
Sandeep Somavarapu 已提交
142
	private async getPreview(remoteUserData: IUserData, lastSyncUserData: IUserData | null, ): Promise<ISyncPreviewResult> {
143
		const remoteGlobalState: IGlobalState = remoteUserData.content ? JSON.parse(remoteUserData.content) : null;
S
Sandeep Somavarapu 已提交
144
		const lastSyncGlobalState = lastSyncUserData && lastSyncUserData.content ? JSON.parse(lastSyncUserData.content) : null;
145 146 147

		const localGloablState = await this.getLocalGlobalState();

S
Sandeep Somavarapu 已提交
148 149 150 151 152 153
		if (remoteGlobalState) {
			this.logService.trace('UI State: Merging remote ui state with local ui state...');
		} else {
			this.logService.trace('UI State: Remote ui state does not exist. Synchronizing ui state for the first time.');
		}

154 155
		const { local, remote } = merge(localGloablState, remoteGlobalState, lastSyncGlobalState);

156
		return { local, remote, remoteUserData, lastSyncUserData };
157 158
	}

159
	private async apply({ local, remote, remoteUserData, lastSyncUserData }: ISyncPreviewResult, forcePush?: boolean): Promise<void> {
S
Sandeep Somavarapu 已提交
160 161 162 163 164 165 166

		const hasChanges = local || remote;

		if (!hasChanges) {
			this.logService.trace('UI State: No changes found during synchronizing ui state.');
		}

167 168
		if (local) {
			// update local
S
Sandeep Somavarapu 已提交
169
			this.logService.trace('UI State: Updating local ui state...');
170
			await this.writeLocalGlobalState(local);
S
Sandeep Somavarapu 已提交
171
			this.logService.info('UI State: Updated local ui state');
172 173 174 175
		}

		if (remote) {
			// update remote
S
Sandeep Somavarapu 已提交
176
			this.logService.trace('UI State: Updating remote ui state...');
S
Sandeep Somavarapu 已提交
177 178
			const content = JSON.stringify(remote);
			const ref = await this.updateRemoteUserData(content, forcePush ? null : remoteUserData.ref);
S
Sandeep Somavarapu 已提交
179
			this.logService.info('UI State: Updated remote ui state');
S
Sandeep Somavarapu 已提交
180
			remoteUserData = { ref, content };
181 182
		}

S
Sandeep Somavarapu 已提交
183
		if (lastSyncUserData?.ref !== remoteUserData.ref) {
184
			// update last sync
S
Sandeep Somavarapu 已提交
185
			this.logService.trace('UI State: Updating last synchronized ui state...');
S
Sandeep Somavarapu 已提交
186
			await this.updateLastSyncUserData(remoteUserData);
S
Sandeep Somavarapu 已提交
187
			this.logService.info('UI State: Updated last synchronized ui state');
188 189 190 191 192 193 194 195
		}
	}

	private async getLocalGlobalState(): Promise<IGlobalState> {
		const argv: IStringDictionary<any> = {};
		const storage: IStringDictionary<any> = {};
		try {
			const content = await this.fileService.readFile(this.environmentService.argvResource);
S
Sandeep Somavarapu 已提交
196
			const argvValue: IStringDictionary<any> = parse(content.value.toString());
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
			for (const argvProperty of argvProperties) {
				if (argvValue[argvProperty] !== undefined) {
					argv[argvProperty] = argvValue[argvProperty];
				}
			}
		} catch (error) { }
		return { argv, storage };
	}

	private async writeLocalGlobalState(globalState: IGlobalState): Promise<void> {
		const content = await this.fileService.readFile(this.environmentService.argvResource);
		let argvContent = content.value.toString();
		for (const argvProperty of Object.keys(globalState.argv)) {
			argvContent = edit(argvContent, [argvProperty], globalState.argv[argvProperty], {});
		}
		if (argvContent !== content.value.toString()) {
			await this.fileService.writeFile(this.environmentService.argvResource, VSBuffer.fromString(argvContent));
		}
	}

}