globalStateSync.ts 8.1 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 } 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 19 20

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

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

27
export class GlobalStateSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser {
28 29

	constructor(
30
		@IFileService fileService: IFileService,
S
Sandeep Somavarapu 已提交
31
		@IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
32 33
		@IUserDataSyncLogService private readonly logService: IUserDataSyncLogService,
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
S
Sandeep Somavarapu 已提交
34
		@IConfigurationService private readonly configurationService: IConfigurationService,
35
	) {
S
Sandeep Somavarapu 已提交
36
		super(SyncSource.GlobalState, fileService, environmentService, userDataSyncStoreService);
37 38 39 40
		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()));
	}

S
Sandeep Somavarapu 已提交
41
	protected getRemoteDataResourceKey(): string { return 'globalState'; }
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
	async pull(): Promise<void> {
		if (!this.configurationService.getValue<boolean>('sync.enableUIState')) {
			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);

			const remoteUserData = await this.getRemoteUserData();

			if (remoteUserData.content !== null) {
				const local: IGlobalState = JSON.parse(remoteUserData.content);
				await this.apply({ local, remote: undefined, remoteUserData });
			}

			// 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> {
		if (!this.configurationService.getValue<boolean>('sync.enableUIState')) {
			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();
S
Sandeep Somavarapu 已提交
86 87
			const remoteUserData = await this.getRemoteUserData();
			await this.apply({ local: undefined, remote, remoteUserData }, true);
88

S
Sandeep Somavarapu 已提交
89
			this.logService.info('UI State: Finished pushing UI State.');
90 91 92 93 94 95
		} finally {
			this.setStatus(SyncStatus.Idle);
		}

	}

S
Sandeep Somavarapu 已提交
96
	async sync(): Promise<void> {
S
Sandeep Somavarapu 已提交
97 98
		if (!this.configurationService.getValue<boolean>('sync.enableUIState')) {
			this.logService.trace('UI State: Skipping synchronizing UI state as it is disabled.');
S
Sandeep Somavarapu 已提交
99
			return;
S
Sandeep Somavarapu 已提交
100 101
		}

102
		if (this.status !== SyncStatus.Idle) {
S
Sandeep Somavarapu 已提交
103
			this.logService.trace('UI State: Skipping synchronizing ui state as it is running already.');
S
Sandeep Somavarapu 已提交
104
			return;
105 106
		}

S
Sandeep Somavarapu 已提交
107
		this.logService.trace('UI State: Started synchronizing ui state...');
108 109 110
		this.setStatus(SyncStatus.Syncing);

		try {
111 112
			const result = await this.getPreview();
			await this.apply(result);
D
Daniel Imms 已提交
113
			this.logService.trace('UI State: Finished synchronizing ui state.');
114 115
		} catch (e) {
			this.setStatus(SyncStatus.Idle);
S
Sandeep Somavarapu 已提交
116
			if (e instanceof UserDataSyncError && e.code === UserDataSyncErrorCode.Rejected) {
117
				// Rejected as there is a new remote version. Syncing again,
S
Sandeep Somavarapu 已提交
118
				this.logService.info('UI State: Failed to synchronise ui state as there is a new remote version available. Synchronizing again...');
119 120 121
				return this.sync();
			}
			throw e;
122 123
		} finally {
			this.setStatus(SyncStatus.Idle);
124 125 126
		}
	}

S
Sandeep Somavarapu 已提交
127 128 129 130 131 132 133 134 135
	async stop(): Promise<void> { }

	async restart(): Promise<void> {
		throw new Error('UI State: Conflicts should not occur');
	}

	resolveConflicts(content: string): Promise<void> {
		throw new Error('UI State: Conflicts should not occur');
	}
136

137 138 139 140 141 142 143 144 145 146 147 148
	async hasLocalData(): Promise<boolean> {
		try {
			const localGloablState = await this.getLocalGlobalState();
			if (localGloablState.argv['locale'] !== 'en') {
				return true;
			}
		} catch (error) {
			/* ignore error */
		}
		return false;
	}

149 150 151 152
	async getRemoteContent(): Promise<string | null> {
		return null;
	}

153
	private async getPreview(): Promise<ISyncPreviewResult> {
154 155 156
		const lastSyncData = await this.getLastSyncUserData();
		const lastSyncGlobalState = lastSyncData && lastSyncData.content ? JSON.parse(lastSyncData.content) : null;

S
Sandeep Somavarapu 已提交
157
		const remoteUserData = await this.getRemoteUserData(lastSyncData);
158
		const remoteGlobalState: IGlobalState = remoteUserData.content ? JSON.parse(remoteUserData.content) : null;
159 160 161

		const localGloablState = await this.getLocalGlobalState();

S
Sandeep Somavarapu 已提交
162 163 164 165 166 167
		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.');
		}

168 169
		const { local, remote } = merge(localGloablState, remoteGlobalState, lastSyncGlobalState);

170 171 172
		return { local, remote, remoteUserData };
	}

S
Sandeep Somavarapu 已提交
173
	private async apply({ local, remote, remoteUserData }: ISyncPreviewResult, forcePush?: boolean): Promise<void> {
S
Sandeep Somavarapu 已提交
174 175 176 177 178 179 180 181

		const hasChanges = local || remote;

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

182 183
		if (local) {
			// update local
S
Sandeep Somavarapu 已提交
184
			this.logService.info('UI State: Updating local ui state...');
185 186 187 188 189
			await this.writeLocalGlobalState(local);
		}

		if (remote) {
			// update remote
S
Sandeep Somavarapu 已提交
190
			this.logService.info('UI State: Updating remote ui state...');
S
Sandeep Somavarapu 已提交
191 192 193
			const content = JSON.stringify(remote);
			const ref = await this.updateRemoteUserData(content, forcePush ? null : remoteUserData.ref);
			remoteUserData = { ref, content };
194 195
		}

S
Sandeep Somavarapu 已提交
196
		if (hasChanges) {
197
			// update last sync
S
Sandeep Somavarapu 已提交
198
			this.logService.info('UI State: Updating last synchronised ui state...');
S
Sandeep Somavarapu 已提交
199
			await this.updateLastSyncUserData(remoteUserData);
200 201 202 203 204 205 206 207
		}
	}

	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 已提交
208
			const argvValue: IStringDictionary<any> = parse(content.value.toString());
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
			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));
		}
	}

}