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

import { Disposable } from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import { isUndefinedOrNull } from 'vs/base/common/types';
9
import { INextStorageService } from 'vs/platform/storage2/common/storage2';
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
import { SQLiteStorage } from 'vs/base/node/storage';
import { ILogService } from 'vs/platform/log/common/log';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { RunOnceScheduler } from 'vs/base/common/async';

enum StorageState {
	None,
	Initialized,
	Closed
}

export class NextStorageServiceImpl extends Disposable implements INextStorageService {
	_serviceBrand: any;

	private static readonly FLUSH_DELAY = 10;

	private _onDidChangeStorage: Emitter<Set<string>> = this._register(new Emitter<Set<string>>());
	get onDidChangeStorage(): Event<Set<string>> { return this._onDidChangeStorage.event; }

	private state = StorageState.None;

	private storage: SQLiteStorage;
	private cache: Map<string, string> = new Map<string, string>();

	private pendingScheduler: RunOnceScheduler;
	private pendingDeletes: Set<string> = new Set<string>();
	private pendingUpdates: Map<string, string> = new Map();
	private pendingPromises: { resolve: Function, reject: Function }[] = [];

	constructor(
		path: string,
		@ILogService private logService: ILogService,
		@IEnvironmentService private environmentService: IEnvironmentService
	) {
		super();

		this.storage = new SQLiteStorage({
			path,
			logging: {
				verbose: this.environmentService.verbose,
				infoLogger: info => this.logService.info(info),
				errorLogger: error => this.logService.error(error)
			}
		});

		this.pendingScheduler = new RunOnceScheduler(() => this.flushPending(), NextStorageServiceImpl.FLUSH_DELAY);
	}

	init(): Promise<void> {
		if (this.state !== StorageState.None) {
			return Promise.resolve(); // either closed or already initialized
		}

		this.state = StorageState.Initialized;

		return this.storage.getItems().then(items => {
			this.cache = items;
		});
	}

	get(key: string, fallbackValue?: any): string {
		const value = this.cache.get(key);

		if (isUndefinedOrNull(value)) {
			return fallbackValue;
		}

		return value;
	}

	getBoolean(key: string, fallbackValue?: boolean): boolean {
		const value = this.get(key);

		if (isUndefinedOrNull(value)) {
			return fallbackValue;
		}

		return value === 'true';
	}

	getInteger(key: string, fallbackValue?: number): number {
		const value = this.get(key);

		if (isUndefinedOrNull(value)) {
			return fallbackValue;
		}

		return parseInt(value, 10);
	}

	set(key: string, value: any): Promise<void> {

		// We remove the key for undefined/null values
		if (isUndefinedOrNull(value)) {
			return this.delete(key);
		}

		// Otherwise, convert to String and store
		const valueStr = String(value);

		// Update in cache and pending
		this.cache.set(key, valueStr);
		this.pendingUpdates.set(key, valueStr);
		this.pendingDeletes.delete(key);

		return this.update();
	}

	delete(key: string): Promise<void> {

		// Remove from cache and add to pending
		this.cache.delete(key);
		if (!this.pendingDeletes.has(key)) {
			this.pendingDeletes.add(key);
		}
		this.pendingUpdates.delete(key);

		return this.update();
	}

	private update(): Promise<void> {

		// Return early if we are already closed
		if (this.state === StorageState.Closed) {
			return Promise.resolve();
		}

		// Schedule
		if (!this.pendingScheduler.isScheduled()) {
			this.pendingScheduler.schedule();
		}

		return new Promise((resolve, reject) => this.pendingPromises.push({ resolve, reject }));
	}

	close(): Promise<void> {

		// Update state
		this.state = StorageState.Closed;

		// Dispose scheduler (no more scheduling possible)
		this.pendingScheduler.dispose();

		// Flush & close
		return this.flushPending().then(() => {
			return this.storage.close();
		});
	}

	private flushPending(): Promise<void> {

		// Get pending data
		const pendingPromises = this.pendingPromises;
		const pendingDeletes = this.pendingDeletes;
		const pendingUpdates = this.pendingUpdates;

		// Reset pending data for next run
		this.pendingPromises = [];
		this.pendingDeletes = new Set<string>();
		this.pendingUpdates = new Map<string, string>();

		return this.storage.deleteItems(pendingDeletes).then(() => this.storage.setItems(pendingUpdates)).then(() => {

			// Resolve pending
			pendingPromises.forEach(promise => promise.resolve());

			// Events (unless closed)
			if (this.state !== StorageState.Closed) {
				const keys = new Set<string>();
				pendingDeletes.forEach(key => keys.add(key));
				pendingUpdates.forEach((value, key) => keys.add(key));
				this._onDidChangeStorage.fire(keys);
			}
		}, error => {

			// Forward error to pending
			pendingPromises.forEach(promise => promise.reject(error));
		});
	}
}