All files / utilities/vscode cancellation.ts

100% Statements 50/50
100% Branches 10/10
100% Functions 12/12
100% Lines 44/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 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                  9x         9x     9x                           7x 1x   6x 6x 1x   5x 1x   1x     5x 3x 1x                             18x   2x     16x                   2x   2x 2x 3x     2x     2x                         16x 1x   1x         15x 15x 2x   2x       15x 15x 15x   15x 31x 31x   28x   16x     12x   15x   15x         20x 20x 20x  
import * as vscode from 'vscode';
 
/**
 * Error type representing the cancellation of an operation.
 */
export class CancellationError extends Error {
	/**
	 * The name of the error.
	 */
	readonly name = 'CancellationError';
 
	/**
	 * HTTP status code representing client-closed request.
	 */
	readonly statusCode: number = 499;
 
	constructor() {
		super('Operation canceled');
	}
}
 
/**
 * Wraps a promise with a cancellation token.
 * @param promise The promise to wrap.
 * @param token The cancellation token.
 * @returns A promise that resolves or rejects based on the original promise, or rejects with a cancellation error if the token is triggered.
 */
export async function withCancellation<T>(
	promise: Promise<T>,
	token?: vscode.CancellationToken
): Promise<T> {
	if (!token) {
		return promise;
	} else {
		return new Promise<T>((resolve, reject) => {
			if (token.isCancellationRequested) {
				reject(new CancellationError());
			} else {
				const subscription = token.onCancellationRequested(() => {
					subscription.dispose();
 
					reject(new CancellationError());
				});
 
				promise.then(
					v => { subscription.dispose(); resolve(v); },
					e => { subscription.dispose(); reject(e); }
				);
			}
		});
	}
}
 
/**
 * Collects any AsyncIterable into an array with VS Code cancellation.
 * @remarks Uses a for-await loop; no dependency on .toArray().
 */
export async function toArrayWithCancellation<T>(
	iterable: AsyncIterable<T>,
	token?: vscode.CancellationToken
): Promise<T[]> {
	if (!token) {
		// Fast path: no token => plain for-await.
		return _toArray(iterable);
	} else {
		// Cancellation-aware: race each next() against a cancel promise.
		return _toArrayWithCancellation(iterable, token);
	}
}
 
/**
 * Collects all items from a generic async iterable into an array.
 * @param iterable A generic async iterable.
 * @returns An array of all items from the iterable.
 */
async function _toArray<T>(iterable: AsyncIterable<T>): Promise<T[]> {
	const result: T[] = [];
 
	try {
		for await (const item of iterable) {
			result.push(item);
		}
	} finally {
		_tryClose(iterable);
	}
 
	return result;
}
 
/**
 * Collects all items from a generic async iterable into an array.
 * @param iterable A generic async iterable.
 * @param token A cancellation token.
 * @returns An array of all items from the iterable.
 */
async function _toArrayWithCancellation<T>(
	iterable: AsyncIterable<T>,
	token: vscode.CancellationToken
): Promise<T[]> {
	if (token.isCancellationRequested) {
		_tryClose(iterable);
 
		throw new CancellationError();
	}
 
	let subscription: vscode.Disposable | undefined;
 
	const cancel = new Promise<never>((_, reject) => {
		subscription = token.onCancellationRequested(() => {
			_tryClose(iterable);
 
			reject(new CancellationError());
		});
	});
 
	try {
		const result: T[] = [];
		const iterator = iterable[Symbol.asyncIterator]();
 
		while (true) {			
			const next = iterator.next();
			const race = await Promise.race([next, cancel]) as IteratorResult<T>;
 
			if (race.done) break;
 
			result.push(race.value);
		}
 
		return result;
	} finally {
		subscription?.dispose();
 
		_tryClose(iterable);
	}
}
 
function _tryClose(iterator: any) {
	try { iterator.return?.(); } catch { }
	try { iterator.close?.(); } catch { }
	try { iterator.destroy?.(); } catch { }
}