src/vs/platform/userDataSync/common/userDataProfilesManifestSync.ts

298 LOC · 219 covered · 79 uncovered · 53 ranges · 585 concepts · 12 introducers · 348 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- abstractSynchronizer.ts ×49
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 { CancellationToken } from '../../../base/common/cancellation.js';
7 > import { toFormattedString } from '../../../base/common/jsonFormatter.js';
8 > import { URI } from '../../../base/common/uri.js';
9 > import { IConfigurationService } from '../../configuration/common/configuration.js';
10 > import { IEnvironmentService } from '../../environment/common/environment.js';
11 > import { IFileService } from '../../files/common/files.js';
12 > import { IStorageService } from '../../storage/common/storage.js';
13 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
14 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
15 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
16 > import { AbstractSynchroniser, IAcceptResult, IMergeResult, IResourcePreview } from './abstractSynchronizer.js';
17 > import { merge } from './userDataProfilesManifestMerge.js';
18 > import { Change, IRemoteUserData, ISyncData, ISyncUserDataProfile, IUserData, IUserDataSyncEnablementService, IUserDataSynchroniser, IUserDataSyncLocalStoreService, IUserDataSyncLogService, IUserDataSyncStoreService, SyncResource, USER_DATA_SYNC_SCHEME, UserDataSyncError, UserDataSyncErrorCode } from './userDataSync.js';
19 >
20 > interface IUserDataProfileManifestResourceMergeResult extends IAcceptResult {
21 > readonly local: { added: ISyncUserDataProfile[]; removed: IUserDataProfile[]; updated: ISyncUserDataProfile[] };
22 > readonly remote: { added: IUserDataProfile[]; removed: ISyncUserDataProfile[]; updated: IUserDataProfile[] } | null;
23 > }
24 >
25 > interface IUserDataProfilesManifestResourcePreview extends IResourcePreview {
26 > readonly previewResult: IUserDataProfileManifestResourceMergeResult;
27 > readonly remoteProfiles: ISyncUserDataProfile[] | null;
28 > }
29 >
30 > export class UserDataProfilesManifestSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser {
31 >
32 > protected readonly version: number = 2;
33 > readonly previewResource: URI = this.extUri.joinPath(this.syncPreviewFolder, 'profiles.json');
34 > readonly baseResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' });
35 > readonly localResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' });
36 > readonly remoteResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' });
37 > readonly acceptedResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' });
38 >
39 > constructor(
40 > profile: IUserDataProfile, userDataSyncService.ts ×19
41 > collection: string | undefined,
42 > @IUserDataProfilesService private readonly userDataProfilesService: IUserDataProfilesService,
43 > @IFileService fileService: IFileService,
44 > @IEnvironmentService environmentService: IEnvironmentService,
45 > @IStorageService storageService: IStorageService,
46 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
47 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
48 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
49 > @IConfigurationService configurationService: IConfigurationService,
50 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
51 > @ITelemetryService telemetryService: ITelemetryService,
52 > @IUriIdentityService uriIdentityService: IUriIdentityService,
53 > ) {
54 > super({ syncResource: SyncResource.Profiles, profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
55 > this._register(userDataProfilesService.onDidChangeProfiles(() => this.triggerLocalChange()));
56 > }
58 > async getLastSyncedProfiles(): Promise<ISyncUserDataProfile[] | null> {
59 > const lastSyncUserData = await this.getLastSyncUserData(); extensionsSync.ts ×17
60 > return lastSyncUserData?.syncData ? parseUserDataProfilesManifest(lastSyncUserData.syncData) : null;
61 > }
63 > async getRemoteSyncedProfiles(refOrLatestData: string | IUserData | null): Promise<ISyncUserDataProfile[] | null> {
64 const lastSyncUserData = await this.getLastSyncUserData();
65 const remoteUserData = await this.getLatestRemoteUserData(refOrLatestData, lastSyncUserData);
66 return remoteUserData?.syncData ? parseUserDataProfilesManifest(remoteUserData.syncData) : null;
67 }
69 > protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean): Promise<IUserDataProfilesManifestResourcePreview[]> {
70 > const remoteProfiles: ISyncUserDataProfile[] | null = remoteUserData.syncData ? parseUserDataProfilesManifest(remoteUserData.syncData) : null; userDataProfilesManifestSync.ts ×8
71 > const lastSyncProfiles: ISyncUserDataProfile[] | null = lastSyncUserData?.syncData ? parseUserDataProfilesManifest(lastSyncUserData.syncData) : null;
72 > const localProfiles = this.getLocalUserDataProfiles();
73 >
74 > const { local, remote } = merge(localProfiles, remoteProfiles, lastSyncProfiles, []);
75 > const previewResult: IUserDataProfileManifestResourceMergeResult = {
76 > local, remote,
77 > content: lastSyncProfiles ? this.stringifyRemoteProfiles(lastSyncProfiles) : null,
78 > localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? Change.Modified : Change.None,
79 > remoteChange: remote !== null ? Change.Modified : Change.None,
80 > };
81 >
82 > const localContent = stringifyLocalProfiles(localProfiles, false);
83 > return [{
84 > baseResource: this.baseResource,
85 > baseContent: lastSyncProfiles ? this.stringifyRemoteProfiles(lastSyncProfiles) : null,
86 > localResource: this.localResource,
87 > localContent,
88 > remoteResource: this.remoteResource,
89 > remoteContent: remoteProfiles ? this.stringifyRemoteProfiles(remoteProfiles) : null,
90 > remoteProfiles,
91 > previewResource: this.previewResource,
92 > previewResult,
93 > localChange: previewResult.localChange,
94 > remoteChange: previewResult.remoteChange,
95 > acceptedResource: this.acceptedResource
96 > }];
97 > }
99 > protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> {
100 > const lastSyncProfiles: ISyncUserDataProfile[] | null = lastSyncUserData?.syncData ? parseUserDataProfilesManifest(lastSyncUserData.syncData) : null; userDataProfilesManifestSync.ts ×1
101 > const localProfiles = this.getLocalUserDataProfiles();
102 > const { remote } = merge(localProfiles, lastSyncProfiles, lastSyncProfiles, []);
103 > return !!remote?.added.length || !!remote?.removed.length || !!remote?.updated.length;
104 > }
106 > protected async getMergeResult(resourcePreview: IUserDataProfilesManifestResourcePreview, token: CancellationToken): Promise<IMergeResult> {
107 > return { ...resourcePreview.previewResult, hasConflicts: false }; userDataProfilesManifestSync.ts ×14
108 > }
110 > protected async getAcceptResult(resourcePreview: IUserDataProfilesManifestResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult> {
111 > /* Accept local resource */ userDataProfilesManifestSync.ts ×14
112 > if (this.extUri.isEqual(resource, this.localResource)) {
113 return this.acceptLocal(resourcePreview);
114 }
116 > /* Accept remote resource */
117 > if (this.extUri.isEqual(resource, this.remoteResource)) {
118 return this.acceptRemote(resourcePreview);
119 }
121 > /* Accept preview resource */
122 > if (this.extUri.isEqual(resource, this.previewResource)) {
123 > return resourcePreview.previewResult;
124 > }
125
126 throw new Error(`Invalid Resource: ${resource.toString()}`);
129 > private async acceptLocal(resourcePreview: IUserDataProfilesManifestResourcePreview): Promise<IUserDataProfileManifestResourceMergeResult> {
130 const localProfiles = this.getLocalUserDataProfiles();
131 const mergeResult = merge(localProfiles, null, null, []);
132 const { local, remote } = mergeResult;
133 return {
134 content: resourcePreview.localContent,
135 local,
136 remote,
137 localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? Change.Modified : Change.None,
138 remoteChange: remote !== null ? Change.Modified : Change.None,
139 };
140 }
142 > private async acceptRemote(resourcePreview: IUserDataProfilesManifestResourcePreview): Promise<IUserDataProfileManifestResourceMergeResult> {
143 const remoteProfiles: ISyncUserDataProfile[] = resourcePreview.remoteContent ? JSON.parse(resourcePreview.remoteContent) : null;
144 const lastSyncProfiles: ISyncUserDataProfile[] = [];
145 const localProfiles: IUserDataProfile[] = [];
146 for (const profile of this.getLocalUserDataProfiles()) {
147 const remoteProfile = remoteProfiles?.find(remoteProfile => remoteProfile.id === profile.id);
148 if (remoteProfile) {
149 lastSyncProfiles.push({ id: profile.id, name: profile.name, collection: remoteProfile.collection });
150 localProfiles.push(profile);
151 }
152 }
153 if (remoteProfiles !== null) {
154 const mergeResult = merge(localProfiles, remoteProfiles, lastSyncProfiles, []);
155 const { local, remote } = mergeResult;
156 return {
157 content: resourcePreview.remoteContent,
158 local,
159 remote,
160 localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? Change.Modified : Change.None,
161 remoteChange: remote !== null ? Change.Modified : Change.None,
162 };
163 } else {
164 return {
165 content: resourcePreview.remoteContent,
166 local: { added: [], removed: [], updated: [] },
167 remote: null,
168 localChange: Change.None,
169 remoteChange: Change.None,
170 };
171 }
172 }
174 > protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [IUserDataProfilesManifestResourcePreview, IUserDataProfileManifestResourceMergeResult][], force: boolean): Promise<void> {
175 > const { local, remote, localChange, remoteChange } = resourcePreviews[0][1]; userDataProfilesManifestSync.ts ×8
176 > if (localChange === Change.None && remoteChange === Change.None) {
177 > this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing profiles.`); userDataProfilesManifestMerge.ts ×1
178 > }
180 > const remoteProfiles = resourcePreviews[0][0].remoteProfiles || [];
181 > if (remoteProfiles.length + (remote?.added.length ?? 0) - (remote?.removed.length ?? 0) > 20) {
182 throw new UserDataSyncError('Too many profiles to sync. Please remove some profiles and try again.', UserDataSyncErrorCode.LocalTooManyProfiles);
183 }
185 > if (localChange !== Change.None) {
186 > await this.backupLocal(stringifyLocalProfiles(this.getLocalUserDataProfiles(), false)); userDataProfilesManifestSync.ts ×4
187 > await Promise.all(local.removed.map(async profile => {
188 > this.logService.trace(`${this.syncResourceLogLabel}: Removing '${profile.name}' profile...`); userDataProfilesManifestSync.ts ×3
189 > await this.userDataProfilesService.removeProfile(profile);
190 > this.logService.info(`${this.syncResourceLogLabel}: Removed profile '${profile.name}'.`);
192 > await Promise.all(local.added.map(async profile => {
193 > this.logService.trace(`${this.syncResourceLogLabel}: Creating '${profile.name}' profile...`); userDataProfilesManifestSync.ts ×1
194 > await this.userDataProfilesService.createProfile(profile.id, profile.name, { icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
195 > this.logService.info(`${this.syncResourceLogLabel}: Created profile '${profile.name}'.`);
197 > await Promise.all(local.updated.map(async profile => {
198 > const localProfile = this.userDataProfilesService.profiles.find(p => p.id === profile.id); userDataProfilesManifestSync.ts ×1
199 > if (localProfile) {
200 > this.logService.trace(`${this.syncResourceLogLabel}: Updating '${profile.name}' profile...`);
201 > await this.userDataProfilesService.updateProfile(localProfile, { name: profile.name, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
202 > this.logService.info(`${this.syncResourceLogLabel}: Updated profile '${profile.name}'.`);
203 > } else {
204 this.logService.info(`${this.syncResourceLogLabel}: Could not find profile with id '${profile.id}' to update.`);
205 }
207 > }
209 > if (remoteChange !== Change.None) {
210 > this.logService.trace(`${this.syncResourceLogLabel}: Updating remote profiles...`); userDataProfilesManifestSync.ts ×14
211 > const addedCollections: string[] = [];
212 > const canAddRemoteProfiles = remoteProfiles.length + (remote?.added.length ?? 0) <= 20;
213 > if (canAddRemoteProfiles) {
214 > for (const profile of remote?.added || []) {
215 > const collection = await this.userDataSyncStoreService.createCollection(this.syncHeaders);
216 > this.logService.trace(`${this.syncResourceLogLabel}: Created collection "${collection}" for "${profile.name}".`);
217 > addedCollections.push(collection);
218 > remoteProfiles.push({ id: profile.id, name: profile.name, collection, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
219 > }
220 > } else {
221 this.logService.info(`${this.syncResourceLogLabel}: Could not create remote profiles as there are too many profiles.`);
222 }
223 > for (const profile of remote?.removed || []) { userDataProfilesManifestSync.ts ×14
224 > remoteProfiles.splice(remoteProfiles.findIndex(({ id }) => profile.id === id), 1); userDataProfilesManifestSync.ts ×3
225 > }
226 > for (const profile of remote?.updated || []) { userDataProfilesManifestSync.ts ×14
227 > const profileToBeUpdated = remoteProfiles.find(({ id }) => profile.id === id); userDataProfilesManifestSync.ts ×1
228 > if (profileToBeUpdated) {
229 > remoteProfiles.splice(remoteProfiles.indexOf(profileToBeUpdated), 1, { ...profileToBeUpdated, id: profile.id, name: profile.name, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
230 > }
231 > }
233 > try {
234 > remoteUserData = await this.updateRemoteProfiles(remoteProfiles, force ? null : remoteUserData.ref);
235 > this.logService.info(`${this.syncResourceLogLabel}: Updated remote profiles.${canAddRemoteProfiles && remote?.added.length ? ` Added: ${JSON.stringify(remote.added.map(e => e.name))}.` : ''}${remote?.updated.length ? ` Updated: ${JSON.stringify(remote.updated.map(e => e.name))}.` : ''}${remote?.removed.length ? ` Removed: ${JSON.stringify(remote.removed.map(e => e.name))}.` : ''}`);
236 > } catch (error) {
237 if (addedCollections.length) {
238 this.logService.info(`${this.syncResourceLogLabel}: Failed to update remote profiles. Cleaning up added collections...`);
239 for (const collection of addedCollections) {
240 await this.userDataSyncStoreService.deleteCollection(collection, this.syncHeaders);
241 }
242 }
243 throw error;
244 }
246 > for (const profile of remote?.removed || []) {
247 > await this.userDataSyncStoreService.deleteCollection(profile.collection, this.syncHeaders); userDataProfilesManifestSync.ts ×3
248 > }
251 > if (lastSyncUserData?.ref !== remoteUserData.ref) {
252 > // update last sync
253 > this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized profiles...`);
254 > await this.updateLastSyncUserData(remoteUserData);
255 > this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized profiles.`);
256 > }
257 > }
259 > async updateRemoteProfiles(profiles: ISyncUserDataProfile[], ref: string | null): Promise<IRemoteUserData> {
260 > return this.updateRemoteUserData(this.stringifyRemoteProfiles(profiles), ref); userDataProfilesManifestSync.ts ×14
261 > }
263 > async hasLocalData(): Promise<boolean> {
264 return this.getLocalUserDataProfiles().length > 0;
265 }
267 > async resolveContent(uri: URI): Promise<string | null> {
268 if (this.extUri.isEqual(this.remoteResource, uri)
269 || this.extUri.isEqual(this.baseResource, uri)
270 || this.extUri.isEqual(this.localResource, uri)
271 || this.extUri.isEqual(this.acceptedResource, uri)
272 ) {
273 const content = await this.resolvePreviewContent(uri);
274 return content ? toFormattedString(JSON.parse(content), {}) : content;
275 }
276 return null;
277 }
279 > private getLocalUserDataProfiles(): IUserDataProfile[] {
280 > return this.userDataProfilesService.profiles.filter(p => !p.isDefault && !p.isTransient); userDataProfilesManifestSync.ts ×8
281 > }
283 > private stringifyRemoteProfiles(profiles: ISyncUserDataProfile[]): string {
284 > return JSON.stringify([...profiles].sort((a, b) => a.name.localeCompare(b.name))); userDataProfilesManifestSync.ts ×14
285 > }
287 > }
288 >
289 > export function stringifyLocalProfiles(profiles: IUserDataProfile[], format: boolean): string {
290 > const result = [...profiles].sort((a, b) => a.name.localeCompare(b.name)).map(p => ({ id: p.id, name: p.name })); userDataProfilesManifestSync.ts ×8
291 > return format ? toFormattedString(result, {}) : JSON.stringify(result);
292 > }
294 > export function parseUserDataProfilesManifest(syncData: ISyncData): ISyncUserDataProfile[] {
295 > return JSON.parse(syncData.content); userDataProfilesManifestSync.ts ×14
296 > }
297
298