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

'use strict';

import * as path from 'path';
import * as crypto from 'crypto';
10
import * as pfs from 'vs/base/node/pfs';
11
import Uri from 'vs/base/common/uri';
12
import { ResourceQueue } from 'vs/base/common/async';
13
import { IBackupFileService, BACKUP_FILE_UPDATE_OPTIONS, BACKUP_FILE_RESOLVE_OPTIONS } from 'vs/workbench/services/backup/common/backup';
14
import { IFileService, ITextSnapshot } from 'vs/platform/files/common/files';
15
import { TPromise } from 'vs/base/common/winjs.base';
16
import { readToMatchingString } from 'vs/base/node/stream';
17
import { ITextBufferFactory } from 'vs/editor/common/model';
B
Benjamin Pasero 已提交
18 19
import { createTextBufferFactoryFromStream, createTextBufferFactoryFromSnapshot } from 'vs/editor/common/model/textModel';
import { keys } from 'vs/base/common/map';
20

B
Benjamin Pasero 已提交
21 22
export interface IBackupFilesModel {
	resolve(backupRoot: string): TPromise<IBackupFilesModel>;
B
Benjamin Pasero 已提交
23 24 25

	add(resource: Uri, versionId?: number): void;
	has(resource: Uri, versionId?: number): boolean;
26
	get(): Uri[];
B
Benjamin Pasero 已提交
27
	remove(resource: Uri): void;
28
	count(): number;
B
Benjamin Pasero 已提交
29 30 31
	clear(): void;
}

B
Benjamin Pasero 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
export class BackupSnapshot implements ITextSnapshot {
	private preambleHandled: boolean;

	constructor(private snapshot: ITextSnapshot, private preamble: string) {
	}

	public read(): string {
		let value = this.snapshot.read();
		if (!this.preambleHandled) {
			this.preambleHandled = true;

			if (typeof value === 'string') {
				value = this.preamble + value;
			} else {
				value = this.preamble;
			}
		}

		return value;
	}
}

B
Benjamin Pasero 已提交
54
export class BackupFilesModel implements IBackupFilesModel {
B
Benjamin Pasero 已提交
55 56
	private cache: { [resource: string]: number /* version ID */ } = Object.create(null);

B
Benjamin Pasero 已提交
57
	public resolve(backupRoot: string): TPromise<IBackupFilesModel> {
B
Benjamin Pasero 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
		return pfs.readDirsInDir(backupRoot).then(backupSchemas => {

			// For all supported schemas
			return TPromise.join(backupSchemas.map(backupSchema => {

				// Read backup directory for backups
				const backupSchemaPath = path.join(backupRoot, backupSchema);
				return pfs.readdir(backupSchemaPath).then(backupHashes => {

					// Remember known backups in our caches
					backupHashes.forEach(backupHash => {
						const backupResource = Uri.file(path.join(backupSchemaPath, backupHash));
						this.add(backupResource);
					});
				});
			}));
		}).then(() => this, error => this);
	}

B
Benjamin Pasero 已提交
77
	public add(resource: Uri, versionId = 0): void {
B
Benjamin Pasero 已提交
78 79 80
		this.cache[resource.toString()] = versionId;
	}

81 82 83 84
	public count(): number {
		return Object.keys(this.cache).length;
	}

B
Benjamin Pasero 已提交
85
	public has(resource: Uri, versionId?: number): boolean {
B
Benjamin Pasero 已提交
86 87 88 89 90 91 92 93 94 95 96 97
		const cachedVersionId = this.cache[resource.toString()];
		if (typeof cachedVersionId !== 'number') {
			return false; // unknown resource
		}

		if (typeof versionId === 'number') {
			return versionId === cachedVersionId; // if we are asked with a specific version ID, make sure to test for it
		}

		return true;
	}

98 99
	public get(): Uri[] {
		return Object.keys(this.cache).map(k => Uri.parse(k));
100 101
	}

B
Benjamin Pasero 已提交
102
	public remove(resource: Uri): void {
B
Benjamin Pasero 已提交
103 104 105
		delete this.cache[resource.toString()];
	}

B
Benjamin Pasero 已提交
106
	public clear(): void {
B
Benjamin Pasero 已提交
107 108 109 110
		this.cache = Object.create(null);
	}
}

111 112
export class BackupFileService implements IBackupFileService {

113 114
	private static readonly META_MARKER = '\n';

115 116
	public _serviceBrand: any;

117
	private backupWorkspacePath: string;
B
Benjamin Pasero 已提交
118

119
	private isShuttingDown: boolean;
B
Benjamin Pasero 已提交
120
	private ready: TPromise<IBackupFilesModel>;
B
Benjamin Pasero 已提交
121
	private ioOperationQueues: ResourceQueue; // queue IO operations to ensure write order
B
Benjamin Pasero 已提交
122

123
	constructor(
124
		backupWorkspacePath: string,
125
		@IFileService private fileService: IFileService
126
	) {
127
		this.isShuttingDown = false;
B
Benjamin Pasero 已提交
128
		this.ioOperationQueues = new ResourceQueue();
129 130 131 132 133 134 135

		this.initialize(backupWorkspacePath);
	}

	public initialize(backupWorkspacePath: string): void {
		this.backupWorkspacePath = backupWorkspacePath;

136
		this.ready = this.init();
D
Daniel Imms 已提交
137 138
	}

139
	private init(): TPromise<IBackupFilesModel> {
B
Benjamin Pasero 已提交
140
		const model = new BackupFilesModel();
141

142
		return model.resolve(this.backupWorkspacePath);
B
Benjamin Pasero 已提交
143 144
	}

145 146 147 148 149 150
	public hasBackups(): TPromise<boolean> {
		return this.ready.then(model => {
			return model.count() > 0;
		});
	}

151
	public loadBackupResource(resource: Uri): TPromise<Uri> {
B
Benjamin Pasero 已提交
152
		return this.ready.then(model => {
B
Benjamin Pasero 已提交
153

154
			// Return directly if we have a known backup with that resource
B
Benjamin Pasero 已提交
155
			const backupResource = this.toBackupResource(resource);
156 157 158
			if (model.has(backupResource)) {
				return backupResource;
			}
159

160
			return void 0;
B
Benjamin Pasero 已提交
161
		});
162 163
	}

164
	public backupResource(resource: Uri, content: ITextSnapshot, versionId?: number): TPromise<void> {
165 166 167 168
		if (this.isShuttingDown) {
			return TPromise.as(void 0);
		}

B
Benjamin Pasero 已提交
169
		return this.ready.then(model => {
170
			const backupResource = this.toBackupResource(resource);
B
Benjamin Pasero 已提交
171
			if (model.has(backupResource, versionId)) {
B
Benjamin Pasero 已提交
172
				return void 0; // return early if backup version id matches requested one
B
Benjamin Pasero 已提交
173
			}
174

175
			return this.ioOperationQueues.queueFor(backupResource).queue(() => {
176 177 178
				const preamble = `${resource.toString()}${BackupFileService.META_MARKER}`;

				// Update content with value
179
				return this.fileService.updateContent(backupResource, new BackupSnapshot(content, preamble), BACKUP_FILE_UPDATE_OPTIONS).then(() => model.add(backupResource, versionId));
180
			});
B
Benjamin Pasero 已提交
181
		});
182 183
	}

184
	public discardResourceBackup(resource: Uri): TPromise<void> {
B
Benjamin Pasero 已提交
185
		return this.ready.then(model => {
186
			const backupResource = this.toBackupResource(resource);
B
Benjamin Pasero 已提交
187

188
			return this.ioOperationQueues.queueFor(backupResource).queue(() => {
189 190
				return pfs.del(backupResource.fsPath).then(() => model.remove(backupResource));
			});
B
Benjamin Pasero 已提交
191
		});
192 193
	}

194
	public discardAllWorkspaceBackups(): TPromise<void> {
195 196
		this.isShuttingDown = true;

B
Benjamin Pasero 已提交
197
		return this.ready.then(model => {
198
			return pfs.del(this.backupWorkspacePath).then(() => model.clear());
B
Benjamin Pasero 已提交
199 200 201
		});
	}

202
	public getWorkspaceFileBackups(): TPromise<Uri[]> {
203
		return this.ready.then(model => {
B
Benjamin Pasero 已提交
204 205
			const readPromises: TPromise<Uri>[] = [];

206
			model.get().forEach(fileBackup => {
K
katainaka0503 已提交
207
				readPromises.push(
B
Benjamin Pasero 已提交
208
					readToMatchingString(fileBackup.fsPath, BackupFileService.META_MARKER, 2000, 10000).then(Uri.parse)
K
katainaka0503 已提交
209
				);
210
			});
B
Benjamin Pasero 已提交
211

212 213 214 215
			return TPromise.join(readPromises);
		});
	}

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
	public resolveBackupContent(backup: Uri): TPromise<ITextBufferFactory> {
		return this.fileService.resolveStreamContent(backup, BACKUP_FILE_RESOLVE_OPTIONS).then(content => {

			// Add a filter method to filter out everything until the meta marker
			let metaFound = false;
			const metaPreambleFilter = (chunk: string) => {
				if (!metaFound && chunk) {
					const metaIndex = chunk.indexOf(BackupFileService.META_MARKER);
					if (metaIndex === -1) {
						return ''; // meta not yet found, return empty string
					}

					metaFound = true;
					return chunk.substr(metaIndex + 1); // meta found, return everything after
				}

				return chunk;
			};

			return createTextBufferFactoryFromStream(content.value, metaPreambleFilter);
		});
237 238
	}

239
	public toBackupResource(resource: Uri): Uri {
240
		return Uri.file(path.join(this.backupWorkspacePath, resource.scheme, this.hashPath(resource)));
D
Daniel Imms 已提交
241
	}
242

243 244
	private hashPath(resource: Uri): string {
		return crypto.createHash('md5').update(resource.fsPath).digest('hex');
245
	}
246
}
B
Benjamin Pasero 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

export class InMemoryBackupFileService implements IBackupFileService {

	public _serviceBrand: any;

	private backups: Map<string, ITextSnapshot> = new Map();

	hasBackups(): TPromise<boolean> {
		return TPromise.as(this.backups.size > 0);
	}

	loadBackupResource(resource: Uri): TPromise<Uri> {
		const backupResource = this.toBackupResource(resource);
		if (this.backups.has(backupResource.toString())) {
			return TPromise.as(backupResource);
		}

		return TPromise.as(void 0);
	}

	backupResource(resource: Uri, content: ITextSnapshot, versionId?: number): TPromise<void> {
		const backupResource = this.toBackupResource(resource);
		this.backups.set(backupResource.toString(), content);

		return TPromise.as(void 0);
	}

	resolveBackupContent(backupResource: Uri): TPromise<ITextBufferFactory> {
		const snapshot = this.backups.get(backupResource.toString());
		if (snapshot) {
			return TPromise.as(createTextBufferFactoryFromSnapshot(snapshot));
		}

		return TPromise.as(void 0);
	}

	getWorkspaceFileBackups(): TPromise<Uri[]> {
		return TPromise.as(keys(this.backups).map(key => Uri.parse(key)));
	}

	discardResourceBackup(resource: Uri): TPromise<void> {
		this.backups.delete(this.toBackupResource(resource).toString());

		return TPromise.as(void 0);
	}

	discardAllWorkspaceBackups(): TPromise<void> {
		this.backups.clear();

		return TPromise.as(void 0);
	}

	toBackupResource(resource: Uri): Uri {
		return Uri.file(path.join(resource.scheme, this.hashPath(resource)));
	}

	private hashPath(resource: Uri): string {
		return crypto.createHash('md5').update(resource.fsPath).digest('hex');
	}
}